个人题解:前缀和求解问题
题目:
标签:
- 恶心。
思路:
- 这道题是考察前缀和。这个没什么难的。难点在于,如何通过所有样例!
- 难点1:采用 long 保存元素,避免溢出问题!
- 难点2:long fu = (long)(favoriteDay + 1) * dailyCap; 这里面如果不加一个强制转换,会导致结果溢出!原因是里面乘法元素全部都是 int 形的,直接乘会导致按照 int 形计算,最后返回一个 int 形给 long,不会报错,但结果不正确!!
题解:
class Solution {
public boolean[] canEat(int[] candiesCount, int[][] queries) {
int length = queries.length, candy_length = candiesCount.length;
long[] pre_candy = new long[candy_length];
pre_candy[0] = candiesCount[0];
for (int i = 1; i < candy_length; ++i) {
pre_candy[i] = pre_candy[i - 1] + candiesCount[i];
}
boolean[] res = new boolean[length];
for (int i = 0; i < length; ++i) {
int favoriteType = queries[i][0], favoriteDay = queries[i][1], dailyCap = queries[i][2];
long fl = favoriteDay + 1;
long fu = (long)(favoriteDay + 1) * dailyCap;
long dl = 1;
long du = pre_candy[favoriteType];
if (favoriteType > 0) {
dl = pre_candy[favoriteType - 1] + 1;
}
if (fl > du || fu < dl) {
res[i] = false;
} else {
res[i] = true;
}
}
return res;
}
}