LeetCode 30 days Challenge - Day 25
本系列將對LeetCode新推出的30天算法挑戰進行總結記錄,旨在記錄學習成果、方便未來查閱,同時望爲廣大網友提供幫助。
Jump Game
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.
Solution
題目要求分析:給定只含有非負元素的整型數組,從第一個位置開始,每一個元素值代表在該位置能夠跳躍到達的最遠距離,判斷給定的數組能否依照規則到達最後一個位置。
解法:
本題採用雙指針思想,儘可能優化了時間複雜度。
以下簡述雙指針的方案:
- 首先,對於
左指針 l
,右指針 r
,每次進入while循環體,我們將檢測兩個指針之間的所有位置,看看這些位置有沒有可能跳轉到最後一個位置,若能,則返回true
。 - 假設不能,那麼我們需要更新兩個指針,且
儘可能使兩個指針移動的足夠快
:l = r + 1
:左指針的更新發生在本次檢測之後,我們期望不要進行重複的檢測來優化時間
,那麼左指針將更新爲本次檢測的最後一個位置的後一個位置
。r = nextr
:在檢測兩個指針中間位置過程中,將能到達的最遠位置,更新給nextr
,nextr
用於記錄下一次while循環應該檢測的右指針位置。
注:參考上方第二個示例的情況,若對while循環不加退出條件,l、r將會一直爲(3, 3);爲避免陷入死循環,檢測到兩次循環的左右指針全部未改變時,提前退出。
bool canJump(vector<int>& nums) {
int n = nums.size() - 1, l = 0, r = 0, nextr;
do {
nextr = nums[r] ? r + 1 : r;
for (int i = l; i <= r; i++) {
if (i + nums[i] >= n) return true;
else nextr = max(nextr, i + nums[i]);
}
l = r+1;
r = nextr;
} while (l != r+1 || r != nextr);
return false;
}
傳送門:Jump Game
2020/4 Karl