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.

Example 1:

Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:

Input: [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum
jump length is 0, which makes it impossible to reach the last index.

貪心法
LeetCode 刷題記錄 45. Jump Game II
不同,這次只需要知道是否可以到達終點即可,不用記錄步數
從頭開始遍歷,首先判斷現在的位置i是否能達到,不能達到直接返回false
然後判斷現在最遠距離是否已經能達到終點,能直接返回true
然後更新最遠距離,繼續循環
c++:

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

java:

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

python:

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        n = len(nums)
        curFarthest = 0
        for i in xrange (n):
            if i > curFarthest: return False
            if curFarthest >= n-1: return True
            curFarthest = max(i + nums[i], curFarthest)
        
        return curFarthest >= n-1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章