[leet code 135]candy
2015-02-27 22:52
190 查看
1 题目
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?
2 思路
按照网上的思路,每个孩子至少有一个糖果,先从左到右遍历一遍,写出递增的糖果数,再从右到左遍历一遍完成递减的糖果数。这种大小与左右两边数据相关的问题,均可以采用这个思路。另外,有另一种空间复杂度O(1),时间复杂度O(n)的思路,可以参考/article/6171320.html。
3 代码
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?
2 思路
按照网上的思路,每个孩子至少有一个糖果,先从左到右遍历一遍,写出递增的糖果数,再从右到左遍历一遍完成递减的糖果数。这种大小与左右两边数据相关的问题,均可以采用这个思路。另外,有另一种空间复杂度O(1),时间复杂度O(n)的思路,可以参考/article/6171320.html。
3 代码
public int candy(int[] ratings) { if(ratings == null || ratings.length == 0) { return 0; } int[] candyNums = new int[ratings.length]; candyNums[0] = 1; for(int i = 1; i < ratings.length; i++) { if(ratings[i] > ratings[i-1]) //如果第i个孩子比第i - 1孩子等级高, { candyNums[i] = candyNums[i-1]+1; } else //每人至少有一个糖果 { candyNums[i] = 1; } } for(int i = ratings.length-2; i >= 0; i--) { if(ratings[i] > ratings[i + 1] && candyNums[i] <= candyNums[ i + 1]) //如果第i个孩子比第i + 1孩子等级高并且糖果比i+1糖果少 { candyNums[i] = candyNums[i + 1] + 1; } } int total = 0; for (int i = 0; i < candyNums.length; i++) { total += candyNums[i]; } return total; }
相关文章推荐
- 【LeetCode 135】Candy (Python)
- leetcode 135: Candy
- Leet code 67. Add Binary
- [leet code] Symmetric Tree
- [leet code] Swap Nodes in Pairs
- [leet code] Permutations
- [leet code] Rotate Image
- LeetCode135 Candy
- [leet code] Valid Sudoku
- leet code - Third Maximum Number
- 【Leet Code】59. Spiral Matrix II---Medium
- Leet Code 2 Add Two Numbers - 链表表示的两个数求和 - Java
- Leet Code 20 Valid Parentheses - 有效括号 - Java
- Leet Code 52 N-Queens II - N皇后问题 - Java
- Leet Code 58 Length of Last Word - 最后一个单词的长度 -Java
- Permutations(Leet Code)
- leetcode || 135、Candy
- 【Leet Code】Longest Substring Without Repeating Characters
- 【Leet Code】Palindrome Number
- LeetCode 135:candy 题解 Python