LeetCode: Candy
2013-11-02 08:45
651 查看
这题就是从左到右对递增的点进行刷点,再从右到左对递增的点进行刷点。时间复杂度和空间复杂度都为O(n)。注意如果两个相邻的点ratings一样,则不必保持candy数一样(个人认为很不合理).
C#
View Code
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
相关文章推荐
- LeetCode – Refresh – Candy
- [LeetCode] 135. candy
- Leetcode之Candy分糖果问题
- [LeetCode] Candy, Solution
- LeetCode:Candy
- LeetCode(135) Candy
- 【leetcode】Candy(python)
- [LeetCode 135] Candy
- 【leetcode】Candy(hard) 自己做出来了 但别人的更好
- LeetCode candy
- Leetcode: Candy
- [LeetCode]Candy
- Candy--LeetCode
- [LeetCode] Candy
- leetcode第16题(candy)
- [LeetCode] Candy
- [leetcode] Candy
- 开始leetcode day9:Candy
- candy-leetcode :只需要遍历一遍的解法
- [LeetCode] Candy