1. 程式人生 > >leetcode135. Candy

leetcode135. Candy

int -- subject ont code spa 糖果 can cte

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