1. 程式人生 > >Java/575. Distribute Candies 分糖果

Java/575. Distribute Candies 分糖果

題目

程式碼部分一(73ms,82.46%)

class Solution {
    public int distributeCandies(int[] candies) {
        Map<Integer, Integer> sister = new HashMap<Integer, Integer>();
        int n = candies.length / 2;
        int j = 0;
        for(int i = 0; i < candies.length; i++){
            if(j >= n)break;
            if(!sister.containsKey(candies[i])){
                sister.put(candies[i], 1);
                j++;
            }
        }
        return sister.size();
    }
}

程式碼部分二(27ms,99.34%)

class Solution {
    public int distributeCandies(int[] candies) {
        boolean[] flag = new boolean[200001];
        int counter = 0;
        for(int i : candies){
            if(flag[i+100000] == false){
                flag[i+100000] = true;
                counter++;
            }
        }
        return counter < candies.length/2 ? counter : candies.length/2;
    }
}