【原创】leetCodeOj --- Candy 解题报告

题目地址:

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

题目内容:

Candy

Total Accepted: 43150 Total Submissions: 203841 Difficulty: Hard

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?

题目解析:

简单来讲,一个数组里的每个小孩都有权值,每个小孩都必须有一颗糖,而如果身边的小孩权值比自己低,那么自己就能多拿糖。

问最少能给几颗糖

容易看出,n个小孩,那么至少n颗糖,我们可以在这个基础上分配糖。

贪心算法:

从权值最小的小孩开始分起,每分到一个小孩时,看他是否比身边小孩的权值大,如果大,则比身边小孩最多糖数再多1;如果小,则不变。

为什么这个算法是对的?

0、由于权值比自己小的小孩已经处理过了,所以,后面不会出现权值比自己小的小孩获得的糖果数更新的情况,因此,自己的糖果数也不用更新。

1、由于每处理一个小孩,该小孩就不用再修改,所以从1块糖处理起时,每个小孩拿到的都是自己可以拿到的最小值。

具体代码:

class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
self.ratings = ratings
if len(ratings) == 0:
return 0
heap = list()
candies = list()
for i in range(len(ratings)):
heap.append({'index':i,'value':ratings[i]})
candies.append(1)
heap = sorted(heap, key=lambda x:x['value'])
for i in range(len(heap)):
self.get_candy(heap[i], candies)
return sum(candies) def get_candy(self, item, candies):
index = item['index']
value = item['value']
if index - 1 >= 0:
if self.ratings[index - 1] < value:
candies[index] = candies[index - 1] + 1
if index + 1 < len(candies):
if self.ratings[index + 1] < value:
if candies[index] < candies[index + 1] + 1:
candies[index] = candies[index + 1] + 1
上一篇:【Linux安全】系统资源监控与进程终止


下一篇:全网最详细的IDEA、Eclipse和MyEclipse之间于Java web项目发布到Tomcat上运行成功的对比事宜【博主强烈推荐】【适合普通的还是Maven方式创建的】(图文详解)