LeetCode 135:candy 题解 Python
来源:互联网 发布:微信诱导付费源码 编辑:程序博客网 时间:2024/06/05 05:57
题意:每个小朋友有一个rating值, 为每个小朋友分配糖果,如果某个小朋友的rating比相邻的某个人高,则他的糖果也要比他多。问最少需要给出去多少糖果
题解:这是一个贪心,先正着扫一边,如果序列递增,则糖果数依次加一,如果遇到变小的则设为1。 得到最少的糖果序列 。
然后再反向贪心一遍。 最后把两个序列求max 然后相加即可
>.< 很久没做过算法一直在做水题。 就当学python了吧。
class Solution: # @param {integer[]} ratings # @return {integer} def candy(self, ratings): num = [1] cnt = 1 for i in range(1,len(ratings)) : if ratings[i]>ratings[i-1] : cnt += 1 else : cnt = 1 num.append(cnt) # ans = num.pop() ans = num[len(ratings)-1] cnt = 1 for i in range(len(ratings)-1,0,-1) : if ratings[i-1]>ratings[i] : cnt += 1 else : cnt = 1 ans += max ( num[i-1], cnt ) return ans if __name__ == '__main__' : a = Solution () ratings = [1,2,3,4,3,2,1] ans2 = a.candy(ratings) print ans2~ ~
虽然实习没什么时间做题。但是还是要每天坚持才行!
0 0
- LeetCode 135:candy 题解 Python
- LeetCode题解:Candy
- LeetCode题解:Candy
- leetcode题解-135. Candy
- LeetCode 题解(89): Candy
- LeetCode题解–135. Candy
- LeetCode Algorithms 135. Candy 题解
- 【leetcode】Candy(python)
- 【LeetCode with Python】 Candy
- 135. Candy Leetcode Python
- [Leetcode][python]Candy
- [Leetcode 135, Hard] Candy
- LeetCode: Candy [135]
- [leetcode 135] Candy
- LeetCode(135) Candy
- [LeetCode 135]Candy
- LeetCode 135 Candy
- leetcode || 135、Candy
- 黑马程序员——继承、抽象类、接口、多态
- DEV GridControl(1)
- QCOM平台子系统通过AP处理异常
- 基于结构分析的句子语义倾向性计算算法(IEEE2013)
- 黑马程序员-oc内存管理(Q)
- LeetCode 135:candy 题解 Python
- iOS的Bitcode是什么?怎么配置?
- UVA 1644 Prime Gap
- oem7f7激活win7时出现Cannot open file C:/OEMSF
- 八大排序算法
- 如何在动态库中使用对话框资源(转) .
- 个人的尚学堂数据库oracle笔记(3)
- flash透明按钮
- JS原型与原型链终极详解