leetcode刷题之贪心算法

贪心算法:

在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的是在某种意义上的局部最优解。

455. Assign Cookies

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.
Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.
Example 1:
Input: [1,2,3], [1,1]
Output: 1
Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
Example 2:
Input: [1,2], [1,2,3]
Output: 2
Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.

  • 解题思路:
    选用最小的糖果去满足要求最小的孩子,这样能够让糖果更大利用化。
class Solution(object):
    def findContentChildren(self, g, s):
        """
        :type g: List[int]
        :type s: List[int]
        :rtype: int
        """
        child = 0
        i = 0
        s.sort()
        g.sort()
        while i < len(s) and child < len(g):
            if g[child] <= s[i]:
                child += 1
            i += 1
        return child
                

376. Wiggle Subsequence

A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence.
For example, [1,7,4,9,2,5] is a wiggle sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, return the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order.
Example 1:
Input: [1,7,4,9,2,5]
Output: 6
Explanation: The entire sequence is a wiggle sequence.
Example 2:
Input: [1,17,5,10,13,15,10,5,16,8]
Output: 7
Explanation: There are several subsequences that achieve this length. One is [1,17,10,13,10,16,8].

python 解答,超过100%的python

  • 思路:
    构建状态机, state有 ‘begin’ , ‘down’,'end’三个状态,利用len1指针来统计摇摆序列的数量,初始阶段为’begin‘状态,当当前数据比前一个数大时state转为’up’状态,当当前数据比前一个数小时state转为’down’状态,当状态发生反转时len1指针才需要加1,其他情况len1不变。
  • 贪心算法在题中的运用:每次找的都是反转前的最大值。
class Solution(object):
    def wiggleMaxLength(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        state = 'begin'
        len1 = 1
        i = 0
        length = len(nums)
        if length < 2:
            return length
        if length == 2:
            if nums[0] == nums[1]:
                return 1
            else:
                return 2
            
        while i < length-1:  
            if state == 'begin':
                if nums[i] < nums[i+1]:
                    state = 'up'
                    len1 += 1
                elif nums[i] > nums[i+1]:
                    state = 'down'
                    len1 += 1
                i += 1
                
            elif state == 'up':
                if nums[i] > nums[i+1]:
                    state = 'down'
                    len1 += 1
                i += 1
                                  
            elif state == 'down':
                if nums[i] < nums[i+1]:
                    state = 'up'
                    len1 += 1
                i += 1
        return len1

402. Remove K Digits

Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.
Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.
Example 1:
Input: num = “1432219”, k = 3
Output: “1219”
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = “10200”, k = 1
Output: “200”
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = “10”, k = 2
Output: “0”
Explanation: Remove all the digits from the number and it is left with nothing which is 0.

  • 思路:
    贪心算法和栈的综合运用,使用贪心算法,将排在左边最大的数删除,栈用来存储结果,如果后一个数大于前一个数,则出栈,一直循环判断得到最后的结果。
class Solution(object):
    def removeKdigits(self, num, k):
        """
        :type num: str
        :type k: int
        :rtype: str
        """
        lists = []
        for i in range(len(num)):
            if k <= 0:
                if i < len(num):
                    lists.append(num[i:])
                    break
            while len(lists) > 0 and k > 0 and num[i] < lists[-1]:
                lists.pop()
                k -= 1
            lists.append(num[i])
        while k > 0:
            if len(lists) == 0:
                return '0'
            lists.pop()
            k -= 1
        if len(lists) == 0:
            return '0'
        s = ''
        for a in lists:
            s += a
        return str(int(s))

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.

python 解答,超过98%

  • 思路
    贪心算法, 假如输入时[2,3,1,1,4],则可以算出每个位置能够走到最远位置:[3,5,4,5,9], 设置指针max_state=1, max_state首先要大于位置i,不然就跳不过去,其次要满足i位置的最远距离要大于max_state,说明还可以继续往后跳,最后max_state能够大于等于顺序表的长度说明能够跳过去。
class Solution(object):
    def canJump(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        max_state = 1
        for i in range(len(nums)):
            if i+1+nums[i] > max_state and max_state > i:
                max_state = i+1+nums[i]
        if max_state >= len(nums):
            return True
        return False
            

猜你喜欢

转载自blog.csdn.net/m0_37327467/article/details/87733569