我正在使用leetcode处理此问题:
给定一个数组糖果和整数extraCandies,其中candies [i]表示和 child 所拥有的糖果数量。
对于每个 child ,检查是否有一种方法可以在 child 之间分配额外的糖果,以使他或她可以在其中拥有最多的糖果。请注意,多个 child 可以拥有最多数量的糖果。
例1:
说明:
我将
console.log('true')
和console.log('false')
放入,以便每当代码成功执行其功能时,我就可以看到true / false的打印内容。但是它只打印一次true
。这是我的代码。请告诉我我错了什么或我错过了什么:
const candies = [2, 3, 5, 1, 3]
const extraCandies = 3;
var kidsWithCandies = (candies, extraCandies) => {
var max = candies.reduce(function(a, b) {
return Math.max(a, b);
});
var min = candies.reduce(function(a, b) {
return Math.min(a, b);
});
console.log(min)
console.log(max)
for (let i = 0; i < candies.length; i++) {
if (candies[i] === max) {
return true
} else if (candies[i] = candies[i] + extraCandies < max) {
return false
} else if (candies[i] = candies[i] + extraCandies > max) {
return true
} else if (candies[i] === min) {
//> max
candies[i] = candies[i] + extraCandies
if (candies[i] > max) {
return true
} else if (candies[i] < max) {
return false
}
}
};
}
最佳答案
这些将通过JavaScript:
const kidsWithCandies = (candies, extraCandies) => {
const maxCandies = Math.max(...candies);
return candies.map(candy => candy + extraCandies >= maxCandies);
};
console.log(kidsWithCandies(candies = [2, 3, 5, 1, 3], extraCandies = 3))
const kidsWithCandies = (candies, extraCandies) => {
let maxCandies = 0;
const greatest = [];
for (const candy of candies) {
(candy > maxCandies) && (maxCandies = candy);
}
for (let index = 0; index < candies.length; ++index) {
greatest.push(candies[index] + extraCandies >= maxCandies);
}
return greatest;
};
console.log(kidsWithCandies(candies = [4,2,1,1,2], extraCandies = 1))
python
class Solution:
def kidsWithCandies(self, candies, extraCandies):
max_candies = max(candies)
return [candy + extraCandies >= max_candies for candy in candies]
java 在Java中,我们将使用
Arrays.stream
:public final class Solution {
public static final List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
int maxCandies = Arrays.stream(candies).max().getAsInt();
return Arrays.stream(candies).mapToObj(candy -> candy + extraCandies >= maxCandies).collect(Collectors.toList());
}
}
运行时是N的顺序。引用文献