LeetCode || Candy
来源:互联网 发布:mdf和ldf恢复数据库 编辑:程序博客网 时间:2024/06/16 00:23
Candy
Total Accepted: 12392 Total Submissions: 68386My SubmissionsThere are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
- Each child must have at least one candy.
- Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
由上述分析可以看出,我们需要记录递减子序列的长度descLen,以及子序列开头第一个人的candy数量descBegCan,在判断当前属于递减子序列的人的candy数时,我们并不能仅仅给当前candy总数加上这个长度,因为可能递减子序列的开头那个人(仅仅是开头这个人)本身已经有很多candy了,那么它不需要加1(就像上面判断到第五六个人3,2时,我们并不需要给第四个人4的candy数加1,因为它已经有了3个了,3>2>1 成立),而要看当前的长度descLen与descBegCan的大小关系,如果长度小于开头那个人的数量,那么仅加上长度减1 即可;如果二者相等,那么需要加上长度。
代码如下:
class Solution {public: int candy(vector<int> &ratings) { int res=0; int lastRat = -1, lastCan = 0, can = 0; int descLen = 0, descBegCan=0; //连续递减子序列的长度和递减序列头部的值 for(int i=0; i<ratings.size(); ++i){ if(ratings[i]>lastRat){ can = lastCan+1; descLen = 0; }else if(ratings[i]==lastRat){ //相邻且rating相等的人candy可以不一样 can = 1; descLen = 0; }else{ can = 1; if(descLen==0) descBegCan = lastCan; descLen++; if(can==lastCan){ if(descLen<descBegCan) res += descLen-1; else if(descLen==descBegCan){ res += descLen; descBegCan++; } } } res += can; lastRat = ratings[i]; lastCan = can; } return res; }};
本方法的空间复杂度为O(1),时间复杂度为O(n),应该属于最好的方法之一了。
0 0
- Leetcode: Candy
- LeetCode:Candy
- [leetcode]Candy
- Leetcode: Candy
- 【leetcode】Candy
- LeetCode:Candy
- [LeetCode] Candy
- [LeetCode]Candy
- [LeetCode] Candy
- 【LeetCode】Candy
- LeetCode | Candy
- Leetcode: Candy
- Candy - LeetCode
- leetcode Candy
- LeetCode Candy
- candy leetcode
- Candy -- LeetCode
- [LeetCode] Candy
- 单源最短路总结
- android webView 的常见问题与高级用法
- ios学习之UIWebView网页视图
- LeetCode——Integer to Roman
- c语言lesson03
- LeetCode || Candy
- 设计模式总结—行为型
- HDU 1250 Hat's Fibonacci 大数加法 进位10000000
- HDU 1133 Buy the Ticket 50,100钱买票,大数乘除法,卡特兰数变形
- If this code works, it was written by Paul DiLascia.
- 暑期入门练习(简单数论,质数筛选)
- OGRE 1.0 至 1.7.3 更新日志
- 标准C程序设计-链表
- c语言文件操作