LeetCode-贪心

十年热恋 提交于 2019-12-01 01:45:51

45. Jump Game II 跳跃游戏 II

https://leetcode.com/problems/jump-game-ii/

题目:给定一个非负整数数组,您最初定位在数组的第一个索引处。数组中的每个元素表示该位置的最大跳转长度。您的目标是达到最小跳数中的最后一个索引。

思路:

class Solution {
    public int jump(int[] nums) {
        int curFarthest = 0, curEnd = 0;
        int count = 0;
        for(int i = 0; i < nums.length-1; i++) {
            curFarthest = Math.max(nums[i]+i, curFarthest);
            if(i == curEnd) {
                count++;
                curEnd = curFarthest;
            }
        }
        return count;
    }
}

 

55. Jump Game 跳跃游戏

https://leetcode.com/problems/jump-game/

题目:给定一个非负整数数组,您最初定位在数组的第一个索引处。数组中的每个元素表示该位置的最大跳转长度。确定是否能够达到最后一个索引。

思路:

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

 

 

贪心:

http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
// http://oj.leetcode.com/problems/jump-game/
// http://oj.leetcode.com/problems/jump-game-ii/
http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
http://oj.leetcode.com/problems/maximum-subarray/
http://oj.leetcode.com/problems/minimum-window-substring/
http://oj.leetcode.com/problems/maximal-rectangle/
http://oj.leetcode.com/problems/longest-substring-without-repeating-characters/

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!