LeetCode 55. Jump Game & 45. Jump Game II题解

来源:互联网 发布:廖雪峰java 编辑:程序博客网 时间:2024/05/16 19:19

55.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

大意:
给出一个非负整数数组,你最初定位在数组的第一个位置。   
数组中的每个元素代表你在那个位置可以跳跃的最大长度。    
判断你是否能到达数组的最后一个位置。

思路:
设置最后可到达的位置是max,遍历数组中的元素。

bool canJump(int* nums, int numsSize) {    if(numsSize <= 1)       return true;    int max = 0;    for(int i = 0; i < numsSize && i <= max;i++){//i<=max限制是因为如果max比i小,那么根本到不了i位置        if(nums[i]+i > max)            max = nums[i] + i;    }    if(max < numsSize-1)          return false;    return true;}

45.Jump Game II
和上一题不同是这次要返回最小次数

思路:如果i大于lastReach,这说明上次的跳不够,所以要再跳一次。

int jump(int* nums, int numsSize) {    if(numsSize == 0)        return 0;    int lastReach = 0,reach = 0,step = 0;    for(int i = 0;i <= reach && i < numsSize;i++){        if(i > lastReach){            step++;            lastReach = reach;        }        if(nums[i] + i > reach)            reach = nums[i] + i;    }    if(reach < numsSize -1)        return 0;    return step;}