您的位置:首页 > 其它

[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), 但是第二种要更简洁明了.

代码如下:

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: