[LeetCode]1431.拥有最多糖果的孩子
这道题比较简单解题思路就是先通过遍历找到拥有最多糖果的孩子有几颗糖果,再把多余的糖果分配给所有孩子,判断该孩子的糖果数是否比拥有最多糖果的孩子多,是为true,否为false。
c++
class Solution {
public:
int Max(vector<int>& candies){
int max = 0;
for(int i = 0; i < candies.size(); i++) {
if(candies[i]>max)max = candies[i];
}
return max;
}
vector<bool> kidsWithCandies(vector<int>& candies, int extraCandies) {
//先找出糖果数最多的孩子(candies的最大值max)
int max = Max(candies);
//分配糖果给其余孩子判断是否大于最大值max,是返回true,否返回false
vector<bool> v;
for(int i = 0; i < candies.size(); i++){
if(candies[i]+extraCandies >= max ){
v.push_back(true);
}else{
v.push_back(false);
}
}
return v;
}
};
找出最大值可以用C++的max_element
int maxCandies = *max_element(candies.begin(), candies.end());
java
class Solution {
public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
int n = candies.length;
int maxCandies = 0;
for (int i = 0; i < n; ++i) {
maxCandies = Math.max(maxCandies, candies[i]);
}
List<Boolean> ret = new ArrayList<Boolean>();
for (int i = 0; i < n; ++i) {
ret.add(candies[i] + extraCandies >= maxCandies);
}
return ret;
}
}
参考
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-candies/solution/yong-you-zui-duo-tang-guo-de-hai-zi-by-leetcode-so/
来源:力扣(LeetCode)