Leetcode专题之贪心法

111 阅读2分钟

贪心法一般都是应用于特别玄学的题,这里做一个贪心法的汇总,持续更新。一般看了题觉得需要找规律的都是贪心法

  1. 781. Rabbits in Forest

There is a forest with an unknown number of rabbits. We asked n rabbits  "How many rabbits have the same color as you?"  and collected the answers in an integer array answers where answers[i] is the answer of the ith rabbit.

Given the array answers, return the minimum number of rabbits that could be in the forest.

 

Example 1:

Input: answers = [1,1,2]
Output: 5
Explanation:
The two rabbits that answered "1" could both be the same color, say red.
The rabbit that answered "2" can't be red or the answers would be inconsistent.
Say the rabbit that answered "2" was blue.
Then there should be 2 other blue rabbits in the forest that didn't answer into the array.
The smallest possible number of rabbits in the forest is therefore 5: 3 that answered plus 2 that didn't.

Example 2:

Input: answers = [10,10,10]
Output: 11
  1. 用hash来统计answers中每个数字出现的次数;
  2. 然后就是开始处理哈希表里面的统计结果了; 例如, 5出现了8次, 那么至少得(8 / (5 + 1) + 1)*(5+1)只兔子;
  • 8 / (5 + 1) * (5 + 1) 代表其中的6只数量为5兔子分别都是同一种颜色,
  • 1 * (5 + 1)代表最后一只没有被整除的兔子,除了这只兔子,还有额外的5只兔子跟他颜色相同
  • 出现次数 % (跟当前兔子有多少只相同的兔子 + 1)只要不为零,不管得几,最后都只剩6只兔子

例子: 如果5出现了6次呢? 至少需要6只兔子; 如果5出现了3次呢? 还是6只兔子;

当val出现了t次, 如果t%(val+1) == 0, 需要(t/(val+1)) (val+1)只兔子; 如果没有整除, 则至少需要(t/(val+1)+1) (val+1)只兔子;

class Solution {
    public int numRabbits(int[] answers) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < answers.length; i++) {
            map.put(answers[i], map.getOrDefault(answers[i], 0) + 1);
        }
        int res = 0;
        for(int y: map.keySet()) {
            int x = map.get(y);
            res += (x / (y + 1)) * (y + 1); 
            if (x % (y + 1) != 0) {
                res += y + 1;
            }
        }
        return res;
    }
}