美文网首页
LeetCode 柠檬水找零问题

LeetCode 柠檬水找零问题

作者: 掉了西红柿皮_Kee | 来源:发表于2020-05-14 10:59 被阅读0次

Record my own stupidity. 20200514


  • 自己的沙雕写法:
class Solution:
   def lemonadeChange(self, bills: List[int]) -> bool:
       # 当前的钱都是整数倍的 因此可以使用贪心算法
       cur = [] # 随时维护的数组
       for bill in bills:
           if bill == 5:
               cur.append(bill)
           if bill == 10:
               if cur.count(5) > 0:
                   idx = cur.index(5)
                   cur.pop(idx)
                   cur.append(10)
               else:
                   return False
           if bill == 20:
               # 找零15
               # 10+5
               if cur.count(10)>0 and cur.count(5)>0:
                   idxs_10 = cur.index(10)
                   cur.pop(idxs_10)
                   idxs_5 = cur.index(5)
                   cur.pop(idxs_5)
                   cur.append(20)
                   
               elif cur.count(5) >= 3:
                   for i in range(3):
                       idxs_5 = cur.index(5)
                       cur.pop(idxs_5)
                   cur.append(20)
               else:
                   return False
       return True

因为用到了list.index()方法,导致增加了很多遍历列表的操作。

  • 大佬题解
class Solution(object): 
    def lemonadeChange(self, bills):
        five = ten = 0
        for bill in bills:
            if bill == 5:
                five += 1
            elif bill == 10:
                if not five: return False
                five -= 1
                ten += 1
            else:
                if ten and five:
                    ten -= 1
                    five -= 1
                elif five >= 3:
                    five -= 3
                else:
                    return False
        return True

只记录零钱的数量,不需要用列表维护。

菜的痛心疾首

相关文章

  • 一起学算法-860. 柠檬水找零

    一、题目 LeetCode-860. 柠檬水找零地址:https://leetcode-cn.com/proble...

  • 每日一题20201210(860. 柠檬水找零)

    860. 柠檬水找零[https://leetcode-cn.com/problems/lemonade-chan...

  • LeetCode 柠檬水找零问题

    Record my own stupidity. 20200514 自己的沙雕写法: 因为用到了list.inde...

  • 【LeetCode】柠檬水找零

    题目描述: 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。顾客排队购买你的产品,(按账单 bills 支付的顺序)...

  • [leetcode]柠檬水找零&&weekly-

    题目链接:柠檬水找零 前文 又是一个周末,第一次参加leetcode的weekly-contest。早上起的晚了,...

  • leetcode 860 柠檬水找零

    这题怎么说,维护五元钞票和十元钞票个数,判断能不能找开就好,纯业务代码!!!可以尝试下dp,题目改一下运行下个人提...

  • leetcode860.柠檬水找零

    题目链接 题目描述: 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。顾客排队购买你的产品,(按账单 bills 支...

  • LeetCode 860. 柠檬水找零

    题目 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购...

  • 37.LeetCode860. 柠檬水找零

    标签: 贪心 难度: 简单 题目描述 我的解法 用一个散列表 gots 作为记账本,键为钞额, 值为当前收到的...

  • 柠檬水找零

    题目: 在柠檬水摊上,每一杯柠檬水的售价为 5 美元。顾客排队购买你的产品,(按账单 bills 支付的顺序)一次...

网友评论

      本文标题:LeetCode 柠檬水找零问题

      本文链接:https://www.haomeiwen.com/subject/bcoznhtx.html