您的位置:首页 > 其它

[leetcode] Candy

2015-08-16 16:25 411 查看
from : https://leetcode.com/problems/candy/
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:
思路 :

举例,

(1) 4 5 5 8 9 3 2 6 7

(2) 1 2 1 2 3 1

(3) 2 1

(4) 4 3 2 1

(5) 5 4 3 2 1

上面是遍历的过程。

(a)如果前一个比后一个大,那么后一个的糖就比前一个多一块;

(b)如果前一个和后一个一样大,那么后一个就分得一块;

(c)如果前一个比后一个小,那么

(c.1)如果前一个比1大,那么这个就分一块;这个必然是第一次分得1块的,那么其前面一个人(如果存在)可能比当前的人多一块以上,记这个人为P,见(2);

(c.2)如果前一个等于1,那么表示这个不能更小了,就要给前面的多分一块;如果P比后面的人多一块以上,那么只要给这个人后面的每个人都多分一块,见(3);

(c.3)如果不满足上面的两点,那么所有P和P后面的人都要多分一块糖,见(4),见(5)。

public class Solution {
public int candy(int[] ratings) {
if(null == ratings || 0 == ratings.length) {
return 0;
}
int n = 1;
int high = 1, low = 0, prenum = 1, hidx = 0;
for(int i=1,len = ratings.length; i<len; ++i) {
int cur = ratings[i], pre = ratings[i-1];
if(cur >= pre) {
if(cur == pre) {
prenum = 1;
n += 1;
} else {
n += ++prenum;
}
hidx = i;
high = prenum;
} else {
if(1 < prenum) {
n += 1;
prenum = 1;
low = 1;
} else if(low+1 < high) {
n += ++low;
} else {
++low;
n += ++high;
}
}
}
return n;
}
}


class Solution {
public:
int candy(vector<int>& ratings) {
int n = 1;
int high = 1, low = 0, prenum = 1, len = ratings.size();

for(int i=1, len = ratings.size(); i<len; ++i) {
int cur = ratings[i], pre = ratings[i-1];
if(cur >= pre) {
if(cur == pre) {
prenum = 1;
n += 1;
} else {
n += ++prenum;
}
high = prenum;
} else {
if(1 < prenum) {
++n;
prenum = low = 1;
} else if(low+1 < high) {
n += ++low;
} else {
++low;
n += ++high;
}
}
}

return n*(len > 0);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: