Leet Code知识点总结 - 575

LeetCode 575. Distribute Candies

考点 难度
Array Easy
题目

Alice has n candies, where the ith candy is of type candyType[i]. Alice noticed that she started to gain weight, so she visited a doctor.

The doctor advised Alice to only eat n / 2 of the candies she has (n is always even). Alice likes her candies very much, and she wants to eat the maximum number of different types of candies while still following the doctor’s advice.

Given the integer array candyType of length n, return the maximum number of different types of candies she can eat if she only eats n / 2 of them.

思路

其实是从可以吃的糖数量和可以选的糖种类中选更小的那个,所以重点是能快速算出糖的种类。我这里的答案是先sort整个array再判断每个糖和它前一个糖的大小是否一致。也可以用hashset(见Madhav1301的答案)。

答案
public int distributeCandies(int[] candyType) {
        int eat = candyType.length/2;
        Arrays.sort(candyType);
        int type = 1;
        for(int i = 1; i < candyType.length; i++){
            if(candyType[i] != candyType[i-1]){
                type ++;
            }
        }
        return Math.min(type, eat);
   }

Guess you like

Origin blog.csdn.net/m0_59773145/article/details/120024069
Recommended