您的位置:首页 > 编程语言 > Python开发

[LeetCode]题解(python):135-Candy

2016-04-05 15:35 519 查看
[b]题目来源:[/b]

  https://leetcode.com/problems/candy/

[b]题意分析:[/b]

  有N个孩子站成一条线。每个孩子有个排名。要求1.每个孩子至少一个糖果,2.相邻的孩子,那么较高排名的孩子得到更多的糖果。返回需要的最少糖果数量。题目中我们可以看到一个隐含的信息。如果相邻孩子排名相同,那么他们的糖果数目可以不一样。

[b]题目思路:[/b]

  这道题目首先要确定整个序列的低洼点,也就是rating[i - 1] >= rating[i] < raing[i+1]。将低洼点的取值取为1,然后往凸点赋值。要注意的是相邻相同的情况,还有凸点的取值。

[b]代码(python):[/b]

class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
size = len(ratings)
if size == 0: return 0
ans = [0 for i in range(size)]
mark,small,d = True,[],{}
i = 0
while i < size:
if mark:
while i < size - 1:
if ratings[i] == ratings[i + 1]:
if i == size - 2:
return size
ans[i] = 1
else:
mark = False
break
i += 1
if i == size - 1:
small.append(i)
ans[i] = 1
break
if ratings[i] < ratings[i + 1]:
small.append(i)
ans[i] = 1;i += 1
while i < size:
if ratings[i] > ratings[i - 1]:
ans[i] = ans[i - 1] + 1
elif ratings[i] == ratings[i - 1]:
ans[i] = 1
else:
d[i - 1] = True
break
i += 1
elif ratings[i] == ratings[i + 1]:
ans[i + 1] = 1
i += 1
else:
i += 1
#print(ans)
#print(small)
for i in small:
#print(small)
j = i - 1
while j >= 0:
if ans[j] == 0 or j not in d:
if ratings[j] > ratings[j + 1]:
ans[j] = ans[j + 1] + 1
else:
ans[j] = 1
elif j > 0 and ans[j] == ans[j - 1]:
ans[j] = ans[j + 1] + 1
break
else:
if ratings[j] == ratings[j + 1]:
break
ans[j] = max(ans[j],ans[j+1]+1)
break
j -= 1
sum = 0
#print(ans,d)
for i in ans:
sum += i
#print(i)
return sum


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