[Leetcode]Candy
2015-02-03 13:33
267 查看
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?
进行两次扫描,第一次扫描的时候从左往右,维护对于每一个小孩左边所需要最少的糖果数量,存入数组num中,第二次扫描从右往左扫,维护右边所需的最少糖果数,并且比较将左边和右边大的糖果数量存入结果数组对应元素中,然后将糖果数累加~时间复杂度为O(n)~两边扫描的方法是一种比较常用的技巧,当遇到变量跟左右元素有关系的题目时可以尝试用这种解法
class Solution:
# @param ratings, a list of integer
# @return an integer
def candy(self, ratings):
if ratings is None or len(ratings) == 0:
return 0
num = [0] * len(ratings)
num[0] = 1
for i in xrange(1, len(ratings)):
if ratings[i] > ratings[i - 1]:
num[i] = num[i - 1] + 1
else:
num[i] = 1
res = num[-1]
for i in xrange(len(ratings) - 2, -1, -1):
cur = 1
if ratings[i] > ratings[i + 1]:
cur = num[i + 1] + 1
num[i] = max(num[i], cur)
res += num[i]
return res
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?
进行两次扫描,第一次扫描的时候从左往右,维护对于每一个小孩左边所需要最少的糖果数量,存入数组num中,第二次扫描从右往左扫,维护右边所需的最少糖果数,并且比较将左边和右边大的糖果数量存入结果数组对应元素中,然后将糖果数累加~时间复杂度为O(n)~两边扫描的方法是一种比较常用的技巧,当遇到变量跟左右元素有关系的题目时可以尝试用这种解法
class Solution:
# @param ratings, a list of integer
# @return an integer
def candy(self, ratings):
if ratings is None or len(ratings) == 0:
return 0
num = [0] * len(ratings)
num[0] = 1
for i in xrange(1, len(ratings)):
if ratings[i] > ratings[i - 1]:
num[i] = num[i - 1] + 1
else:
num[i] = 1
res = num[-1]
for i in xrange(len(ratings) - 2, -1, -1):
cur = 1
if ratings[i] > ratings[i + 1]:
cur = num[i + 1] + 1
num[i] = max(num[i], cur)
res += num[i]
return res
相关文章推荐
- Candy:对样例存在困惑的一道leetcode
- [leetcode 135] Candy
- [LeetCode] 130: Candy
- LeetCode – Refresh – Candy
- leetCode 刷题记录 Candy
- LeetCode 解题报告 Candy
- LeetCode Candy 两种解法
- leetCode Candy解题分享
- leetcode || 135、Candy
- [LeetCode 135] Candy
- leetcode - Candy
- Candy [leetcode]
- [LeetCode]Candy
- Leetcode-Candy
- LeetCode :: Candy
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- Candy--LeetCode
- [leetcode]Candy
- leetcode Candy
- 【leetcode】Candy