【leetcode】贪心算法

贪心法,又称贪心算法贪婪算法、或称贪婪法,是一种在每一步选择中都采取在当前状态下最好或最优(即最有利)的选择,从而希望导致结果是最好或最优的算法。比如在旅行推销员问题中,如果旅行员每次都选择最近的城市,那这就是一种贪心算法。

 

贪心算法在有最优子结构的问题中尤为有效。最优子结构的意思是局部最优解能决定全局最优解。简单地说,问题能够分解成子问题来解决,子问题的最优解能递推到最终问题的最优解。

贪心算法与动态规划的不同在于它对每个子问题的解决方案都做出选择,不能回退。动态规划则会保存以前的运算结果,并根据以前的结果对当前进行选择,有回退功能。

55. 跳跃游戏

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

整个程序的思路就是,找到为0的位置,如果没有为0的位置就一定可以到达终点,如果有,看有0的位置之前的能否跳过0,能跳过就能到达终点,否则不能到达终点。

class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        for i in range(len(nums) - 1):
            if nums[i] == 0:
                temp = nums[0:i+1][::-1]
                count = 0
                flag = False
                for item in temp:
                    if item > count:
                        flag = True
                    count += 1
                if flag == False:
                    return False
        return True

122. 买卖股票的最佳时机 II

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

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        sums = 0
        i = 0
        while i < len(prices) - 1:
            if prices[i + 1] > prices[i]:
                sums += prices[i + 1] - prices[i]
                i += 1
            else:
                i += 1
        return sums    

134. 加油站

https://leetcode-cn.com/problems/gas-station/description/

https://blog.csdn.net/qq_36755175/article/details/80298830

需要再看

class Solution(object):
    def canCompleteCircuit(self, gas, cost):
        """
        :type gas: List[int]
        :type cost: List[int]
        :rtype: int
        """
        sums = 0
        current = 0
        index = 0
        if sum(gas) < sum(cost):
            return -1
        for i in range(len(cost)):#设定到达i站时剩余油量为current
            if (current + gas[i]) < cost[i]:
                index = i + 1
                current = 0
            else:
                current += gas[i] - cost[i]
            sums += gas[i] - cost[i]
        if sums >= 0:#设定所有站点剩余油量之和为sums,若sums>=0,则可以遍历完
            return index
        else:
            return -1

376. 摆动序列

https://leetcode-cn.com/problems/wiggle-subsequence/description/

class Solution(object):
    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) <= 1:
            return len(nums)
        ans = 1
        dif = nums[0] - nums[1]
        if dif != 0:
            ans += 1
        for i in range(2, len(nums)):
            if nums[i] != nums[i - 1]:
                if dif * (nums[i - 1] - nums[i]) <= 0:
                    ans += 1
                    dif = nums[i - 1] - nums[i]
        return ans

392. 判断子序列

https://leetcode-cn.com/problems/is-subsequence/description/

class Solution(object):
    def isSubsequence(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        s = list(s)
        t = list(t)
        for i in range(len(s)):
            if s[i] in t:
                index = t.index(s[i])
                t = t[index + 1:]
            else:
                return False
        return True

402. 移掉K位数字

https://leetcode-cn.com/problems/remove-k-digits/description/

需要再看

class Solution(object):
    def removeKdigits(self, num, k):
        """
        :type num: str
        :type k: int
        :rtype: str
        """
        if k >= len(num):
            return '0'
        i = 0
        while i < len(num) - 1 and k > 0:
            if int(num[i]) > int(num[i + 1]):
                num = num[:i] + num[i + 1:]
                if i > 0:
                    i -= 1
                k -= 1
            else:
                i += 1
        num = num[:len(num) - k]
        return str(int(num))

406. 根据身高重建队列

https://leetcode-cn.com/problems/queue-reconstruction-by-height/description/

452. 用最少数量的箭引爆气球

https://leetcode-cn.com/problems/minimum-number-of-arrows-to-burst-balloons/description/

https://blog.csdn.net/qqzj_bupt/article/details/53325983

class Solution(object):
    def findMinArrowShots(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        n = len(points)
        if n < 1:
            return 0
        else:
            points = sorted(points, key = lambda x:(x[0],x[1]))
            start = points[0][0]
            end = points[0][1]
            count = 1
            for i in range(1,n):
                if points[i][0] <= end:
                    start = points[i][0]
                    end = min(end, points[i][1])
                else:
                    count += 1
                    start = points[i][0]
                    end = points[i][1]
        return count

 

    原文作者:贪心算法
    原文地址: https://blog.csdn.net/weixin_39915444/article/details/81203514
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞