Loading

LeetCode-贪心

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;
    }
}

121. Best Time to Buy and Sell Stock 股票买卖的最佳时机

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

题目:假设您有一个数组,其中ith元素是第一天给定股票的价格。如果只允许您完成最多一笔交易(即购买一只股票并出售一股票),则设计一种算法来寻找最大利润。注意,在你买股票之前,你不能卖股票。

思路:

class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        int buy = Integer.MAX_VALUE;
        for(int price : prices){
            buy = Math.min(buy, price);
            res = Math.max(res, price - buy);
        }
        return res;
    }
}

 

贪心:

// 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/

 

posted @ 2019-10-10 10:52  brynchen  阅读(124)  评论(0)    收藏  举报