Leetcode-1431. The child with the most candies (enumeration method)

1431. Child with the most candies (enumeration method)

  1. The child with the most candies (simple brute force)
    link: https://leetcode-cn.com/problems/kids-with-the-greatest-number-of-candies/

method 1

class Solution {
    
    
    public List<Boolean> kidsWithCandies(int[] candies, int extraCandies) {
    
    
        List<Boolean> List=new ArrayList();
        int max=Integer.MIN_VALUE;
        for(int i=0;i<candies.length;i++){
    
    
            if(candies[i]>max){
    
    
                max=candies[i];
            }
        }

        for(int i=0;i<candies.length;i++){
    
    
            if((candies[i]+extraCandies)>=max){
    
    
                List.add(true);
            }else{
    
    
                List.add(false);
            }
        }
        return List;
    }
}

Method 2 (after optimization)

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;
    }
}



Continuously updating...

Guess you like

Origin blog.csdn.net/weixin_44325444/article/details/106466968