LeetCode: Jump Game II

来源:互联网 发布:2003年网络歌曲大全 编辑:程序博客网 时间:2024/05/24 04:30

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.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

class Solution {public:    int jump(int A[], int n) {        if(n == 0 || n == 1)            return 0;        if(A[0] >= n-1)            return 1;        int index = 0;        int max = 0;        int nextIndex = 0;        int step = 1;        while(index < n)        {            max = 0;            nextIndex = 0;            for(int i = 1; i <= A[index]; i++)            {                if(A[index+i] + index +i >= n-1)                    return step+1;                 if(A[index+i] + index + i > max)                {                    max = A[index+i] + index + i;                    nextIndex = index+i;                }            }            index = nextIndex;            step++;        }    }};


Round 2:

class Solution {public:    int jump(vector<int>& nums) {if(nums.size() <= 1)return 0;if(nums[0] >= nums.size()-1)return 1;        int index = 0;int steps = 1;while(index < nums.size()){int maxstep = -1;int maxIndex = 0;for(int i = index+1; i <= index + nums[index]; i++){if(i + nums[i] >= nums.size()-1){return steps+1;}else{if(i + nums[i] > maxstep){maxstep = i + nums[i];maxIndex = i;}}}if(maxstep == -1)return -1;steps++;index = maxIndex;}    }};



0 0
原创粉丝点击