题目地址
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;
}
}