題目詳情
給定一個非負整數數組,你最初位於數組的第一個位置。
數組中的每個元素代表你在該位置可以跳躍的最大長度。
你的目標是使用最少的跳躍次數到達數組的最後一個位置。
示例:
輸入: [2,3,1,1,4]
輸出: 2
解釋: 跳到最後一個位置的最小跳躍數是 2。
從下標爲 0 跳到下標爲 1 的位置,跳 1 步,然後跳 3 步到達數組的最後一個位置。
說明:
假設你總是可以到達數組的最後一個位置。
——題目難度:困難
說明中的:假設你總是可以到達數組的最後一個位置。意思當然是不會有{2, 4, 5, 0, 0, 0, 0, 0, 0, 1} 這類情況發生
-代碼1
class Solution {
public:
inline int Max(int x, int y){
return x>y? x:y;
}
int jump(vector<int>& nums) {
int n = nums.size();
if(n==0) return 0; //開始在起點,直接到抵達終點
int maxPos = 0;
int count = 0;
int end = 0;
int i;
for(i=0;i<n-1;i++)
{
maxPos = Max(maxPos,i+nums[i]);
if(i == end) {
end = maxPos; //確定下一步的最遠下標
count++;
}
}
return count;
}
};
結果
-代碼2
class Solution {
public:
inline int Max(int x, int y){
return x>y? x:y;
}
int jump(vector<int>& nums) {
int n = nums.size();
if(n==0) return 0; //開始在起點,直接到抵達終點
int maxPos = 0;
int count = 0;
int end = 0;
int i;
for(i=0;i<n-1;i++)
{
maxPos = Max(maxPos,i+nums[i]);
if(i == end) {
end = maxPos; //確定下一步的最遠下標
count++;
if(end == n-1) return count;
}
}
return count;
}
};
結果