今天才思敏捷,竟然一道困难题都做出来了,虽然来来回回改了好几次。
使用贪心算法:
class Solution {
public int jump(int[] nums) {
int pos = 0;
int len = nums[0];
int max = 0;
int ret = 0;
int result = 0;
int length = nums.length;
while(pos != length-1){
if(pos+len>=length){
len = length-1-pos;
}
for(int i = 1;i<=len;i++){
if(pos+i==length-1){
return ++result;
}
if(max<(i+nums[pos+i])){
max = i+nums[pos+i];
ret = i;
}
//max = max>(i+nums[pos+i])?max:(i+nums[pos+i]);
}
max = 0;
pos+=ret;
result++;
len = nums[pos];
}
return result;
}
}
官方的就瞧着简洁顺眼多了。
class Solution {
public int jump(int[] nums) {
int length = nums.length;
int end = 0;
int maxPosition = 0;
int steps = 0;
for (int i = 0; i < length - 1; i++) {
maxPosition = Math.max(maxPosition, i + nums[i]);
if (i == end) {
end = maxPosition;
steps++;
}
}
return steps;
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/jump-game-ii/solution/tiao-yue-you-xi-ii-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。