leetcode刷题笔记-Greedy贪婪算法

330. Patching Array

leetcode刷题笔记-Greedy贪婪算法_第1张图片

leetcode刷题笔记-Greedy贪婪算法_第2张图片 

class Solution(object):
    def minPatches(self, nums, n):
        i, far, re = 0, 0, 0
        nums = sorted(nums)
        while far < n :
            if i < len(nums) and nums[i] <= far + 1:
                far += nums[i]
                i += 1
            else:
                re += 1
                far += far+1
        return re

 

452. Minimum Number of Arrows to Burst Balloons

leetcode刷题笔记-Greedy贪婪算法_第3张图片

先按end排序,每次射在end的位置。如果下一个气球的start< end, 那么下一个气球也会被射破。 

class Solution(object):
    def findMinArrowShots(self, points):
        if not points: return 0
        points = sorted(points, key = lambda x: x[1])
        res = 1
        end = points[0][1]
        for ball in points[1:]:
            if ball[0] > end:
                res += 1
                end = ball[1]
        return res

 

316. Remove Duplicate Letters

leetcode刷题笔记-Greedy贪婪算法_第4张图片

每次找最小的字母 

class Solution(object):
    def removeDuplicateLetters(self, s):  #  O(n)
        if not s: 
            return ''
        count = collections.Counter(s)
        pos = 0
        for i, c in enumerate(s):
            if c < s[pos]: pos = i  # find the leftmost smallest letter 
            count[c] -= 1
            if count[c] == 0: 
                break
        
        return s[pos] + self.removeDuplicateLetters(s[pos+1:].replace(s[pos], ''))

另外一种方法

leetcode刷题笔记-Greedy贪婪算法_第5张图片

45. Jump Game II

leetcode刷题笔记-Greedy贪婪算法_第6张图片

看完直接DP做, 倒数第二个test OTL。后改为greedy, 思路其实差不多。

leetcode刷题笔记-Greedy贪婪算法_第7张图片

你可能感兴趣的:(Algorithm)