您的位置:首页 > 其它

LeetCode: Candy

2013-11-02 08:45 651 查看
这题就是从左到右对递增的点进行刷点,再从右到左对递增的点进行刷点。时间复杂度和空间复杂度都为O(n)。注意如果两个相邻的点ratings一样,则不必保持candy数一样(个人认为很不合理).

class Solution {
public:
int candy(vector<int> &ratings) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> res(ratings.size(), 1);
for (int i = 1; i < ratings.size(); i++)
if (ratings[i] > ratings[i-1]) res[i] = res[i-1] + 1;
for (int i = ratings.size()-2; i >= 0; i--)
if (ratings[i] > ratings[i+1]) res[i] = max(res[i], res[i+1] + 1);
int ans = 0;
for (int i = 0; i < res.size(); i++) ans += res[i];
return ans;
}
};


C#

public class Solution {
public int Candy(int[] ratings) {
int[] res = new int[ratings.Length];
for (int i = 0; i < ratings.Length; i++) res[i] = 1;
for (int i = 1; i < ratings.Length; i++) {
if (ratings[i] > ratings[i-1]) res[i] = res[i-1] + 1;
}
for (int i = ratings.Length-2; i >= 0; i--) {
if (ratings[i] > ratings[i+1]) res[i] = Math.Max(res[i], res[i+1] + 1);
}
int ans = 0;
for (int i = 0; i < res.Length; i++) ans += res[i];
return ans;
}
}


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