LeetCode 题解(171): 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.

题解:

用maxCover表示所能覆盖到的最远位置,动态修改maxCover。

C++版:

class Solution {
public:
    bool canJump(vector<int>& nums) {
        if(nums.size() == 1)
            return true;
        if(nums.size() > 1 && nums[0] == 0)
            return false;
        int last = nums.size() - 1;    
        int maxCover = 0;
        for(int i = 0; i <= maxCover && i < last; i++) {
            if(i + nums[i] > maxCover)
                maxCover = i + nums[i];
            if(maxCover >= last)
                return true;
        }
        return false;
    }
};

Java版:

public class Solution {
    public boolean canJump(int[] nums) {
        int maxCover = 0;
        for(int i = 0; i <= maxCover && i < nums.length; i++) {
            if(i + nums[i] > maxCover)
                maxCover = i + nums[i];
            if(maxCover >= nums.length - 1)
                return true;
        }
        return false;
    }
}

Python版:

class Solution:
    # @param {integer[]} nums
    # @return {boolean}
    def canJump(self, nums):
        maxCover = 0
        i = 0
        while i <= maxCover and i < len(nums):
            if i + nums[i] > maxCover:
                maxCover = i + nums[i]
            if maxCover >= len(nums) - 1:
                return True
            i += 1
        return False


你可能感兴趣的:(LeetCode,Algorithm,面试题)