leetcode - Candy
2013-12-16 08:59 张汉生 阅读(224) 评论(0) 编辑 收藏 举报
1 class Solution { 2 public: 3 struct info{ 4 int rate; 5 int index; 6 info(int r, int i):rate(r), index(i){} 7 bool operator<(const info & b)const{ 8 return rate < b.rate; 9 } 10 }; 11 int candy(vector<int> &ratings) { 12 int n = ratings.size(); 13 if (n <= 0) 14 return 0; 15 vector<info> vi; 16 for (int i = 0; i < n; i++){ 17 vi.push_back(info(ratings[i], i)); 18 } 19 sort(vi.begin(), vi.end()); 20 vector<int> rlt(n, 0); 21 for (int i = 0; i < n; i++){ 22 int val = 1; 23 int index = vi[i].index; 24 if (index>0 && ratings[index - 1] < ratings[index] && rlt[index - 1] >= val) 25 val = rlt[index-1] + 1; 26 if (index < n - 1 && ratings[index + 1] < ratings[index] && rlt[index + 1] >= val) 27 val = rlt[index + 1] + 1; 28 rlt[index] = val; 29 } 30 int sum = 0; 31 for (int i = 0; i < n; i++) 32 sum += rlt[i]; 33 return sum; 34 } 35 };