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

贪心算法

【LeetCode 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.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

题解

   题目要求从数组nums的最左端走到数组的最右端,数组上每个元素代表最多可以走多少步。贪心的思路如下:

    用nDistance记录当前i之前可以走的最远距离。如果distance< i,即代表即使再怎么走也不能到达i。当到达i时,nums[i]+i,代表从i能走的最远距离,如果该值大于或等于数组大小减一,证明可以到达数组最后的位置。否则,更新nDistance,nDistance=max(nDistance, nums[i]+i)代表能到达的最远距离。

【代码】

    bool canJump(vector& nums) {
    	int nSize = nums.size();
    	if (nSize < 2)
    		return true;
    
    	int nDistance = 0;
    	for (int i = 0; i < nSize && i <= nDistance; i++) {
    	    if (i + nums[i] >= nSize - 1)
    	        return true;
    	    if (nDistance < i + nums[i])
    	        nDistance = i + nums[i];
    	}
    	
    	return false;
    }



【LeetCode 45. Jump Game II】

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

Note:
You can assume that you can always reach the last index.

题解

    与上题不同的地方在于该数组肯定可以从最左端走到最右端,并求出最少步数。难点在于什么时候需要为步数加一,答案是当前的i超过了前一步的最远位置。所以引入nLast变量记录上一步能到达的最远位置。nCur、nStep、nLast的初始值均为0。当遍历到i的时候,如果i超过了nLast(即上一步能到达的最远位置),说明步数需要加1,此时仍需要更新nLast为当前最远位置nCur。全程只需遍历1次数组,而且空间复杂度为常量。

【代码】

    int jump(vector& nums) {
    	int nSize = nums.size();
    	if (nSize < 2)
    		return 0;
    	if (nSize == 2)
    	    return 1;
    
        int nStep = 0;
        int nCur = 0;
        int nLast = 0;
        for(int i = 0; i < nSize; i ++) {
            if(nLast < i) {
                nStep ++;
                nLast = nCur;
            }
            
            if (nums[i] + i > nCur)
                nCur = nums[i] + i;
        }
        return nStep;
    }


你可能感兴趣的:(C++)