leetcode刷题日记2020-10-08

88 阅读1分钟

反转字符串

leetcode-cn.com/problems/re…

思路

无难度,双指针即可,注意特殊条件和循环终止条件

代码

class Solution(object):
    def reverseString(self, s):
        """
        :type s: List[str]
        :rtype: None Do not return anything, modify s in-place instead.
        """
        n = len(s)
        if n > 1:
            head, tail = 0, n - 1
            while head < tail:
                s[head], s[tail] = s[tail], s[head]
                head += 1
                tail -= 1

柠檬水找零

leetcode-cn.com/problems/le…

思路

本题思路比较直接,不用考虑太多迭代递归等等,直接遍历即可,需要注意:

  1. 找零优先使用较大币值

代码

class Solution(object):
   def lemonadeChange(self, bills):
       """
       :type bills: List[int]
       :rtype: bool
       """
       remain_cash = dict()
       remain_cash[5] = 0
       remain_cash[10] = 0
       remain_cash[20] = 0
       for bill in bills:
           if bill == 5:
               remain_cash[5] += 1
           elif bill == 10:
               if remain_cash[5] <= 0:
                   return False
               else:
                   remain_cash[5] -= 1
               remain_cash[10] += 1
           else:
               if remain_cash[10] > 0 and remain_cash[5] > 0:
                   remain_cash[10] -= 1
                   remain_cash[5] -= 1
               elif remain_cash[5] >= 3:
                   remain_cash[5] -= 3
               else:
                   return False
               remain_cash[20] += 1
       return True

买卖股票的最佳时机 II

leetcode-cn.com/problems/be…

思路

当天可售出再买回,因此用贪心算法即可

代码

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        result = 0
        for i in range(1, len(prices)):
            profit = prices[i] - prices[i-1]
            if profit > 0:
                result += profit
        return result