1.LeetCode135题目链接
https://leetcode-cn.com/problems/candy/submissions/
2.题目解析
该题直接采用暴力就可以搞定,老师分发糖果,分成两次便利数组就可以了。需要注意的是,第一次遍历不需要相当于赋值,第二次遍历就有了第一次的值,需要坐下判断。记录的值是否比将要变化的小。这种解法由于多次循环,容易超时,解题过程中有打印,导致超时。。
public static int candy(int[] ratings) {
int[] all = new int[ratings.length];
for (int i = 0; i < ratings.length; i++) {
all[i] = 1;
}
for (int i = 1; i < ratings.length; i++) {
if (ratings[i - 1] < ratings[i]) {
all[i] = all[i - 1] + 1;
}
}
for (int i = ratings.length - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1] && all[i] <= all[i + 1]) {
all[i] = all[i + 1] + 1;
}
}
int sum = 0;
for (int i = 0; i < all.length; i++) {
sum += all[i];
}
return sum;
}