题目:
https://leetcode-cn.com/problems/task-scheduler/
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class _621_LeastInterval { // 模拟 public int leastInterval(char[] tasks, int n) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for (char c : tasks) { map.put(c, map.getOrDefault(c, 0) + 1); } int m = map.size(); List<Integer> nextValid = new ArrayList<>(); List<Integer> rest = new ArrayList<>(); for (Map.Entry<Character, Integer> entry : map.entrySet()) { nextValid.add(1); rest.add(entry.getValue()); } int time = 0; for (int i = 0; i < tasks.length; i++) { ++time; int minNextValid = Integer.MAX_VALUE; for (int j = 0; j < m; j++) { if (rest.get(j) != 0) { minNextValid = Math.min(minNextValid, nextValid.get(j)); } } time = Math.max(time, minNextValid); int best = -1; for (int j = 0; j < m; j++) { if (rest.get(j) != 0 && nextValid.get(j) <= time) { if (best == -1 || rest.get(j) > rest.get(best)) { best = j; } } } nextValid.set(best, time + n + 1); rest.set(best, rest.get(best) - 1); } return time; } // 构造 public int leastInterval1(char[] tasks, int n) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int maxExec = 0; for (char c : tasks) { int exec = map.getOrDefault(c, 0) + 1; map.put(c, exec); maxExec = Math.max(maxExec, exec); } int m = map.size(); int maxCount = 0; for (Map.Entry<Character, Integer> entry : map.entrySet()) { if (entry.getValue() == maxExec) { maxCount++; } } return Math.max((maxExec - 1) * (n + 1) + maxCount, tasks.length); } }