[leetcode] Candy
2015-08-16 16:25
411 查看
from : https://leetcode.com/problems/candy/
There 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:
思路 :
举例,
(1) 4 5 5 8 9 3 2 6 7
(2) 1 2 1 2 3 1
(3) 2 1
(4) 4 3 2 1
(5) 5 4 3 2 1
上面是遍历的过程。
(a)如果前一个比后一个大,那么后一个的糖就比前一个多一块;
(b)如果前一个和后一个一样大,那么后一个就分得一块;
(c)如果前一个比后一个小,那么
(c.1)如果前一个比1大,那么这个就分一块;这个必然是第一次分得1块的,那么其前面一个人(如果存在)可能比当前的人多一块以上,记这个人为P,见(2);
(c.2)如果前一个等于1,那么表示这个不能更小了,就要给前面的多分一块;如果P比后面的人多一块以上,那么只要给这个人后面的每个人都多分一块,见(3);
(c.3)如果不满足上面的两点,那么所有P和P后面的人都要多分一块糖,见(4),见(5)。
There 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:
思路 :
举例,
(1) 4 5 5 8 9 3 2 6 7
(2) 1 2 1 2 3 1
(3) 2 1
(4) 4 3 2 1
(5) 5 4 3 2 1
上面是遍历的过程。
(a)如果前一个比后一个大,那么后一个的糖就比前一个多一块;
(b)如果前一个和后一个一样大,那么后一个就分得一块;
(c)如果前一个比后一个小,那么
(c.1)如果前一个比1大,那么这个就分一块;这个必然是第一次分得1块的,那么其前面一个人(如果存在)可能比当前的人多一块以上,记这个人为P,见(2);
(c.2)如果前一个等于1,那么表示这个不能更小了,就要给前面的多分一块;如果P比后面的人多一块以上,那么只要给这个人后面的每个人都多分一块,见(3);
(c.3)如果不满足上面的两点,那么所有P和P后面的人都要多分一块糖,见(4),见(5)。
public class Solution { public int candy(int[] ratings) { if(null == ratings || 0 == ratings.length) { return 0; } int n = 1; int high = 1, low = 0, prenum = 1, hidx = 0; for(int i=1,len = ratings.length; i<len; ++i) { int cur = ratings[i], pre = ratings[i-1]; if(cur >= pre) { if(cur == pre) { prenum = 1; n += 1; } else { n += ++prenum; } hidx = i; high = prenum; } else { if(1 < prenum) { n += 1; prenum = 1; low = 1; } else if(low+1 < high) { n += ++low; } else { ++low; n += ++high; } } } return n; } }
class Solution { public: int candy(vector<int>& ratings) { int n = 1; int high = 1, low = 0, prenum = 1, len = ratings.size(); for(int i=1, len = ratings.size(); i<len; ++i) { int cur = ratings[i], pre = ratings[i-1]; if(cur >= pre) { if(cur == pre) { prenum = 1; n += 1; } else { n += ++prenum; } high = prenum; } else { if(1 < prenum) { ++n; prenum = low = 1; } else if(low+1 < high) { n += ++low; } else { ++low; n += ++high; } } } return n*(len > 0); } };
相关文章推荐
- POJ 3087-Shuffle'm Up(map+模拟)
- js 秒表计时器(开始,停止,清零)
- Android 开源框架Universal-Image-Loader完全解析(四)UNIVERSAL IMAGE LOADER. PART 3---ImageLoader详解
- Google APAC 2016 University Graduates Test(google校招笔试)
- npm模块管理器
- (大数据工程师学习路径)第四步 SQL基础课程----select详解
- 如何加密Url防止被黑
- hdu1003 最大子序列的和
- static 关键字的作用
- hdu 字典树
- Android学习心得(12) --- APK签名keystore
- C++函数的重载、覆盖和隐藏区别
- 中文编码杂谈
- bzoj4199&uoj131: [Noi2015]品酒大会
- Codeforces Round 459 D. Pashmak and Parmida's problem 树状数组求逆序数 变形
- 广度优先搜索
- Hive启动报错无法找到class— java.lang.NoClassDefFoundError
- html5新特性总结
- hdu1081 To the Max
- COJ 1287 求匹配串在模式串中出现的次数