题目链接: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:
- 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?
第一次解题思路:
public class Solution {
public int candy(int[] ratings) {
if (ratings == null || ratings.length == 0) {
return 0;
}
int[] num = new int[ratings.length];
num[0] = 1;
for (int i=1; i<ratings.length; i++) {
// 后一个比前一个得分小
if (ratings[i] < ratings[i-1]) {
num[i] = 1;
for (int j=i; j>0; j--) {
if (ratings[j] < ratings[j-1] && num[j] == num[j-1]) {
num[j-1]++;
} else {
break;
}
}
} else if (ratings[i] == ratings[i-1]) {
num[i] = 1;
} else {
num[i] = num[i-1]+1;
}
}
int sum = 0;
for (int i:num ) {
sum += i;
}
return sum;
}
}
提交后执行测试例超时,经过分析,觉得应该是前面的嵌套循环太耗时(因为每走一步都要往回看一下),考虑优化一下。
第二次解题思路:
public class Solution {
public int candy(int[] ratings) {
if (ratings == null || ratings.length == 0) {
return 0;
}
int sum = 0;
// 局部降序序列起始位置预分配的糖果数
int localFirstPosVal = 1;
// 局部降序序列的长度
int localDescSeqLen = 1;
for (int i=1; i<ratings.length; i++) {
// 后一个比前一个得分小
if (ratings[i] < ratings[i-1]) {
localDescSeqLen++;
} else {
sum = getDesSeqSum(localFirstPosVal, localDescSeqLen, sum);
if (ratings[i] == ratings[i-1]) {
localFirstPosVal = 1;
} else if (ratings[i] > ratings[i-1] && localDescSeqLen > 1) {
localFirstPosVal = 2;
} else if (ratings[i] > ratings[i-1] && localDescSeqLen == 1) {
localFirstPosVal += 1;
}
localDescSeqLen = 1;
}
}
return getDesSeqSum(localFirstPosVal, localDescSeqLen, sum);
}
// 计算降序序列的糖果总数
public int getDesSeqSum(int localFirstPosVal, int localDescSeqLen, int sum) {
if (localDescSeqLen >= localFirstPosVal) {
sum += (1+localDescSeqLen)*localDescSeqLen/2;
} else {
sum += localFirstPosVal;
sum += localDescSeqLen*(localDescSeqLen-1)/2;
}
return sum;
}
}
暂时先这样吧,后面有时间再改进改进。。。