leetcode 135: Candy
来源:互联网 发布:彩虹秒赞源码 编辑:程序博客网 时间:2024/05/29 17:20
Two method can be used here.
The first one is using greedy algorithm twice from begin to end and from end to begin. if the current rating is bigger than the previous one, the number will be added into the sum will increase by 1. Using this method will require you to create an array to save the result of the first scan.
The second method is just scan the ratings for one time. If ratings[i]>ratings[i-1], add the number to be added. If ratings[i]==ratings[i-1], make the number be 1. And if ratings[i]<ratings[i-1], add another loop to find the end of the descending sequence, and then give that child 1 candy, so the whole candy given to the sequence can be determined.
class Solution {public: int candy(vector<int>& ratings) { if(ratings.size()<=1) return ratings.size(); int sum=1,num=1,pre=1;//pre is to save the candy for the start of a descending sequence for(int i=1;i<ratings.size();i++) { if(ratings[i]<ratings[i-1]) { int j=i; while(j<ratings.size()&&ratings[j]<ratings[j-1]) j++;//after the loop, j will be one position after the end int len=j-i;//i is the second in the sequence if(pre<len+1)//len+1 is the minimum candy child i-1 should have sum+=len+1-pre; sum+=(1+len)*len/2; i=j-1; num=1; } else { if(ratings[i]>ratings[i-1]) num++; else num=1; sum+=num; pre=num; } } return sum; }};
0 0
- [Leetcode 135, Hard] Candy
- LeetCode: Candy [135]
- [leetcode 135] Candy
- LeetCode(135) Candy
- [LeetCode 135]Candy
- LeetCode 135 Candy
- leetcode || 135、Candy
- [leetcode-135]Candy(java)
- leetcode 135: Candy
- leetCode #135 Candy
- 【LeetCode-135】Candy
- Leetcode (135) Candy
- LeetCode(135)Candy
- Leetcode. 135 Candy(Hard)
- LeetCode 135 Candy
- LeetCode 135 : Candy
- leetcode 135 —— Candy
- LeetCode 135:candy 题解 Python
- 老版本AMI的根EBS大小问题
- iOS之观察者模式(Observer Pattern)
- 推荐一个Android开源项目-AisenWeiBo
- 关于单链表带环的一系列问题
- OC语法04
- leetcode 135: Candy
- hdu 2085 java 核反应堆
- oc NSString/NSArray/NSNumber
- 利用观察者模式来获取线程中的数据或者回调函数
- pat(A)1041. Be Unique(哈希)
- GoAhead网页提交内容
- LaTeX 代码片插入语法【转】
- error : identifier “atomicAdd” is undefined
- 安装JSP