135. Candy
2015-04-19 11:05
155 查看
题目:
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?
链接: http://leetcode.com/problems/candy/
题解:
贪婪法,O(n) space的比较简单,可以左右各来一遍,然后加起来。 不过要尝试更好的公司,还需要练习O(1) space的解法。二刷时再解决。
Time Complexity - O(n),Space Complexity - O(n)。
Reference:
https://leetcode.com/discuss/76/does-anyone-have-a-better-idea https://leetcode.com/discuss/43581/solutions-given-explanation-time-with-space-other-with-space https://leetcode.com/discuss/16463/a-simple-solution https://leetcode.com/discuss/8501/my-accepted-o-n-o-1-solution https://leetcode.com/discuss/23835/one-pass-constant-space-java-solution
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?
链接: http://leetcode.com/problems/candy/
题解:
贪婪法,O(n) space的比较简单,可以左右各来一遍,然后加起来。 不过要尝试更好的公司,还需要练习O(1) space的解法。二刷时再解决。
Time Complexity - O(n),Space Complexity - O(n)。
public class Solution { public int candy(int[] ratings) { if(ratings == null || ratings.length == 0) return 0; int len = ratings.length; int[] candies = new int[len]; candies[0] = 1; for(int i = 1; i < len; i++) { if(ratings[i] > ratings[i - 1]) candies[i] = candies[i - 1] + 1; else candies[i] = 1; } int sum = candies[len - 1]; for(int i = len - 2; i >= 0; i--) { if(ratings[i] > ratings[i + 1]) if(candies[i] <= candies[i + 1]) candies[i] = candies[i + 1] + 1; sum += candies[i]; } return sum; } }
Reference:
https://leetcode.com/discuss/76/does-anyone-have-a-better-idea https://leetcode.com/discuss/43581/solutions-given-explanation-time-with-space-other-with-space https://leetcode.com/discuss/16463/a-simple-solution https://leetcode.com/discuss/8501/my-accepted-o-n-o-1-solution https://leetcode.com/discuss/23835/one-pass-constant-space-java-solution
相关文章推荐
- LeetCode 135. Candy
- 135. Candy
- LeetCode题解–135. Candy
- 135. Candy
- 135. Candy
- 【LeetCode】135. Candy
- [leetcode] 【数组】 135. Candy
- LeetCode 135. Candy
- [Leetcode] 135. Candy 解题报告
- [算法分析与设计] leetcode 每周一题: 135. Candy
- Leetcode 135. Candy
- 135. Candy Leetcode Python
- Hard-题目34:135. Candy
- 135. Candy
- Leetcode 135. Candy
- leetcode题解-135. Candy
- leetcode 135. Candy
- LeetCode 135. Candy (O(n)时间 O(n)和O(1)空间的两种实现)
- 135. Candy
- 135. Candy 考验逻辑能力的时候到了