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();
    }
}
  1. 创建 sister 用于保存分给妹妹糖果的种类

  2. 循环数组 candies ,当循环超过一半糖果时跳出循环

  3. 每遇到一个“糖果”,判断sister里面是否有该类糖果,若没有则加入 sister 内

  4. j++

  5. 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;
    }
}
  1. 创建 boolean[] (默认 false,长度可以根据题目,数组的数字大小设定)
  2. 遍历 candies 若 flag[] 中未记录该种糖果,进行记录(true),计数器+1
  3. 当糖果种类小于 candies.length/2,返回糖果种类,大于则返回candies.length/2

猜你喜欢

转载自blog.csdn.net/qq_38959715/article/details/82814437