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

题目来源:

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


 

题意分析:

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


 

题目思路:

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


 

代码(python):

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

 

posted @ 2016-04-05 15:35  Ry_Chen  阅读(395)  评论(0编辑  收藏  举报