leetcode1431.拥有最多糖果的孩子

思路

  其实题目的示例解释已经很明确了,只要遍历数组每个元素:
{ c a n d i e s [ i ] + e x t r a C a n d i e s > = m a x ( c a n d i e s [ ] ) 返回true c a n d i e s [ i ] + e x t r a C a n d i e s < m a x ( c a n d i e s [ ] ) 返回false \begin{cases} candies[i]+extraCandies>=max(candies[]) &\text{返回true}\\ candies[i]+extraCandies<max(candies[]) &\text{返回false}\\ \end{cases} {candies[i]+extraCandies>=max(candies[])candies[i]+extraCandies<max(candies[])返回true返回false

代码
class Solution {
	public List<Boolean> kidsWithCandies(int[] candies, int extraCandies){
		List<Boolean> list = new ArrayList<Boolean>();
		int length = candies.length;
		int flag=0; //最大值标志位(数组下标值)		
		for(int i=1;i<length;i++) {
			if(candies[i]>candies[flag]) flag=i;
		}		
		for(int i=0;i<length;i++) {	
			if(candies[i]+extraCandies>=candies[flag])
				list.add(true);
			else list.add(false);
		}
		return list;
	}
}
  • 时间复杂度O(n),空间复杂度O(1)
  • 初始化List<Boolean> list = null时,执行list.add()会出错,改成List<Boolean> list = new ArrayList<Boolean>();就对了,这是为什么呢?——官方文档List<E>是接口,有许多子类,若要初始化,必须指明实现的哪个类。
  • 评论区找最大值有别的写法,可以注意一下:
        for (int candy : candies) {
            max=Math.max(max , candy);
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值