leetcode 135: Candy
2015-08-18 22:34
681 查看
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.
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; } };
相关文章推荐
- android 之 Notification 实例
- Zoom属性的使用介绍(IE私有属性)
- 新学习到的windows快捷键
- Heavy Transportation
- HDOJ 4455 Substrings 递推+树状数组
- 通讯录 oc
- 【程序员电子刊精选】小技术团队管理工具大比拼
- sprintf,你知道多少?
- JAVA多线程和并发基础面试问答
- 多图片/文件上传 - SwfUpload/PlUpload
- OpenGL ES TEXTURE_2D
- 新手笔记之关键字return、break和continue的用法
- Linux 基础一之计算机原理、内核原理、发展历程
- 六度分离
- JavaScript 编程
- 华为OJ(记负均正)
- Java心得16
- [hdu5396 Expression]区间DP
- Android中的进程
- [ JavaScript ] JavaScript 实现继承.