码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode135. Candy

时间:2017-10-05 19:36:11      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:tar   child   sub   solution   higher   val   span   代码   leetcode   

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?

问题如上。

先放上一种方法的实现,以下代码在不考虑数组越界的情况下可以输出正确结果。

 1 class Solution{
 2   public:
 3     int candy(vector<int> &ratings){
 4         int start = 0, end, count = 0; //start=right
 5         int candyCount[1000];          //储存每个人的糖果数量
 6         ratings.push_back(-1);
 7         if (ratings.size() == 2)    return 1;
 8         for (int i = 0; i < ratings.size(); ++i){
 9             if ((ratings[i] <= ratings[i - 1] && ratings[i] < ratings[i + 1]) || (i - 1 < 0 && ratings[i] < ratings[i + 1]) || (i + 1 > ratings.size() - 1 && ratings[i] < ratings[i - 1])){
10                 candyCount[i] = 1;
11                 end = i;
12                 if (end == start)   continue;
13                 vector<int>::iterator maxelem = max_element(ratings.begin() + start, ratings.begin() + end);
14                 int flag = std::distance(ratings.begin(), maxelem);
15                 for (int m = start + 1; m < flag; ++m)
16                     ratings[m] > ratings[m - 1] ? candyCount[m] = candyCount[m - 1] + 1 : candyCount[m] = candyCount[m - 1];
17                 for (int n = end - 1; n > flag; --n){
18                     ratings[n] > ratings[n + 1] ? candyCount[n] = candyCount[n + 1] + 1 : candyCount[n] = candyCount[n + 1];
19                     if ((end == ratings.size() - 1) && (n == end - 1))  candyCount[n]--;
20                 }
21                 if (ratings[flag] == ratings[flag + 1]){
22                     candyCount[flag - 1] < candyCount[flag + 1] ? candyCount[flag] = candyCount[flag + 1] : candyCount[flag] = candyCount[flag - 1] + 1;
23                     while ((ratings[flag] == ratings[flag + 1])&&(flag+1<ratings.size()))
24                         candyCount[flag + 1] = candyCount[flag++];
25                 }else{
26                     candyCount[flag - 1] > candyCount[flag + 1] ? candyCount[flag] = candyCount[flag - 1] + 1 : candyCount[flag] = candyCount[flag + 1] + 1;
27                 }
28                 start = i;
29             }
30         }
31         for (int k = 0; k < ratings.size() - 1; ++k)
32             count += candyCount[k];
33         return count;
34     }
35 };

写的又臭又长。。。

leetcode135. Candy

标签:tar   child   sub   solution   higher   val   span   代码   leetcode   

原文地址:http://www.cnblogs.com/yeqingqian/p/7629816.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!