标签:private lin least get char try ast ash new
Given a char array representing tasks CPU need to do.
It contains capital letters A to Z where different letters represent different tasks.
Tasks could be done without original order.
Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks,
there must be at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
解法一: 计算得到词频最大的字符,该字符相邻最大的数组偏移小于 n
通过 HashMap 统计词频,PriorityQueue 保证有序性
public int leastInterval(char[] tasks, int n) {
Map<Character, Integer> freqs = new HashMap<>();
for (int i = 0; i < tasks.length; i++)
freqs.put(tasks[i], freqs.getOrDefault(tasks[i], 0) + 1);
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(
(a,b) -> a.getValue() != b.getValue() ? b.getValue() - a.getValue() : a.getKey() - b.getKey());
pq.addAll(freqs.entrySet());
int count = 0;
int maxFreq = pq.peek().getValue();
while (!pq.isEmpty() && pq.peek().getValue() == maxFreq) {
pq.poll();
count ++;
}
return Math.max(tasks.length, (maxFreq - 1) * (n + 1) + count);
}
解法二: 通过 HashMap 统计原始词频, LinkedHash 根据 Map.Entry.getValue() 进行排序
public int leastInterval(char[] tasks, int n) {
Map<Character, Integer> freqs = new HashMap<>();
for (int i = 0; i < tasks.length; i++)
freqs.put(tasks[i], freqs.getOrDefault(tasks[i], 0) + 1);
freqs = sortByValue(freqs);
int maxFreq = freqs.entrySet().iterator().next().getValue();
int count = 0;
for (Map.Entry<Character, Integer> entry : freqs.entrySet()) {
if (entry.getValue() == maxFreq)
count ++;
else
break;
}
return Math.max(tasks.length, (maxFreq - 1) * (n + 1) + count);
}
private Map<Character, Integer> sortByValue(Map<Character, Integer> map) {
List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
list.sort((o1, o2) -> !o1.getValue().equals(o2.getValue()) ? Integer.compare(o2.getValue(), o1.getValue()) : Character.compare(o1.getKey(), o2.getKey()));
Map<Character, Integer> newMap = new LinkedHashMap<>();
for (Map.Entry<Character, Integer> entry : list)
newMap.put(entry.getKey(), entry.getValue());
return newMap;
}
标签:private lin least get char try ast ash new
原文地址:https://www.cnblogs.com/janh/p/10713793.html