[算法][贪心算法][leetcode]2244. 完成所有任务需要的最少轮数

题目地址

https://leetcode.cn/problems/minimum-rounds-to-complete-all-tasks/description/

错误解法(暴力解法)

  class Solution {
    public int minimumRounds(int[] tasks) {
     int ans =0;
        //先用一个hashmap记录每个key值出现的次数
        //判断他们是否能被2或者3整除
        HashMap<Integer,Integer> countMap = new HashMap();
        int tasksLen=tasks.length;

        for(int i=0;i<tasksLen;i++){
            if(countMap.containsKey(tasks[i])){
                int count = countMap.get(tasks[i]);
                count++;
                countMap.put(tasks[i],count);
            }else{
                countMap.put(tasks[i],1);
            }
        }

        for (Integer value : countMap.values()) {
            if(value%2 !=0 && value%3!=0 && value%5!=0){
                return -1;
            }else if(value%2 ==0 && value%3==0){
                ans+=value/3;
            }else if(value%2 ==0 && value%3 !=0){
                ans+=value/2;
            }else if(value%2 !=0 && value%3 ==0){
                ans+=value/3;
            }else if (value%5 ==0){
                ans+=(value/5)*2;
            }
        }

        return ans;
    }
}

测试用例
[69,65,62,64,70,68,69,67,60,65,69,62,65,65,61,66,68,61,65,63,60,66,68,66,67,65,63,65,70,69,70,62,68,70,60,68,65,61,64,65,63,62,62,62,67,62,62,61,66,69]

错误原因:

等于8的时候会多加了一次!!

正确解法(贪心)

题解

  class Solution {
    public int minimumRounds(int[] tasks) {
        int ans =0;
        //先用一个hashmap记录每个key值出现的次数
        //判断他们是否能被2或者3整除
        HashMap<Integer,Integer> countMap = new HashMap();
        int tasksLen=tasks.length;

        for(int i=0;i<tasksLen;i++){
            if(countMap.containsKey(tasks[i])){
                int count = countMap.get(tasks[i]);
                count++;
                countMap.put(tasks[i],count);
            }else{
                countMap.put(tasks[i],1);
            }
        }

         for(Integer value :countMap.values()){
            if (value == 1){
                return -1;
            }
            ans += value/3;
            
            if (value%3 !=0){
                ans++;
            }
        }

        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值