1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class Solution { public int leastInterval(char[] tasks, int n) { int time = 0; int count = 0; Map<Character, Integer> times = new HashMap<>(); for (char task : tasks) { times.put(task, times.getOrDefault(task, 0) + 1); } Map<Character, Integer> cd = new HashMap<>(); for (char key : times.keySet()) { cd.put(key, 0); }
while (count != tasks.length) { boolean flag = false; for (char key : mostElement(times)) { if (times.get(key) > 0 && cd.get(key) == 0) { time++; times.put(key, times.get(key) - 1); count++; cd.put(key, n); flag = true; for (char k : times.keySet()) { if (k != key && cd.get(k) != 0) { cd.put(k, cd.get(k) - 1); } } break; } } if (!flag) { time++; for (char key : times.keySet()) { if (cd.get(key) > 0) { cd.put(key, cd.get(key) - 1); } } } } return time; }
private List<Character> mostElement(Map<Character, Integer> map) { List<Character> list = new ArrayList<>(map.keySet()); list.sort((x, y) -> Integer.compare(map.get(y), map.get(x))); return list; } }
|