[leetcode] 135. Candy 解题报告
2016-05-06 14:05
579 查看
题目链接: 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:
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?
思路: 自己想了一个思路比较麻烦,利用栈来维护一个递减序列.
写完之后又看了一下别人怎么写的, 发现只需要从左往右更新一遍计数, 再从右往左扫描更新一遍计数就可以, 这种思路比较容易理解.
两种代码时间复杂度都是O(n), 但是第二种要更简洁明了.
代码如下:
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:
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?
思路: 自己想了一个思路比较麻烦,利用栈来维护一个递减序列.
写完之后又看了一下别人怎么写的, 发现只需要从左往右更新一遍计数, 再从右往左扫描更新一遍计数就可以, 这种思路比较容易理解.
两种代码时间复杂度都是O(n), 但是第二种要更简洁明了.
代码如下:
class Solution { public: int candy(vector<int>& ratings) { if(ratings.size() ==0) return 0; stack<int> st; int sum = 1, num = 1, gap = 0; st.push(ratings[0]); for(int i =1; i<ratings.size(); i++) { if(ratings[i] > st.top()) { while(!st.empty()) st.pop(); num++; } else if(ratings[i] < st.top()) { sum += st.size(); if(num >1) gap = num - 1; if(gap >= 1) sum--, gap--; num = 1; } else if(ratings[i] == st.top()) { while(!st.empty()) st.pop(); gap = 0; num = 1; } st.push(ratings[i]); sum += num; } return sum; } };
class Solution { public: int candy(vector<int>& ratings) { int sum = 0; vector<int> vec(ratings.size(), 1); for(int i = 1; i< ratings.size(); i++) if(ratings[i] > ratings[i-1]) vec[i]=vec[i-1] +1; for(int i = ratings.size()-2; i>=0; i--) if(ratings[i] > ratings[i+1] && vec[i]<=vec[i+1]) vec[i] = vec[i+1] + 1; for(auto val: vec) sum += val; return sum; } };第二种参考: https://leetcode.com/discuss/92299/simple-c-dp-solution-36ms-beats-88%25-submissions
相关文章推荐
- java集合------HashMap
- Easticsearch通信方式_API
- pip install Scrapy 报错解决总结
- Mac上面用来录屏的软件(录制gif图片或者mov)
- linq语句hwere多条件查询
- (STL)vector的常用指令
- 字符串的排列
- 关于报错Self referencing loop detected with type的原因以及解决办法
- Android:利用SharedPreferences实现自动登录
- MFC 模态、非模态窗口引发的系列事件及函数
- UVa 101 The Blocks Problem(vector)
- ubuntu安装mysql
- Android的IPC方式
- 用结点实现链表LinkedList,用数组和结点实现栈Stack,用数组和结点链表实现队列Queue
- LeetCode 之 Perfect Squares
- adb 发送broadcast广播
- Android Stadio常用快捷键及基本设置
- 字段他表选择中的快速检索设置
- ros PCC叠加内网一个网卡多个IP互访解决
- ansilbe 入门001、ansible的介绍