|
1 | 1 | class Solution {
|
2 |
| - public boolean isNStraightHand(int[] hand, int W) { |
3 |
| - if (hand.length % W != 0) { |
4 |
| - return false; |
5 |
| - } |
6 |
| - Map<Integer, Integer> counterMap = new HashMap<>(); |
7 |
| - Set<Integer> set = new TreeSet<>(); |
8 |
| - for (int num : hand) { |
9 |
| - counterMap.put(num, counterMap.getOrDefault(num, 0) + 1); |
10 |
| - set.add(num); |
11 |
| - } |
12 |
| - Iterator<Integer> iter = set.iterator(); |
13 |
| - Integer curr = iter.next(); |
14 |
| - while (counterMap.get(curr) > 0) { |
15 |
| - int temp = curr; |
16 |
| - for (int i = 0; i < W; i++) { |
17 |
| - if (counterMap.getOrDefault(temp, 0) == 0) { |
18 |
| - return false; |
| 2 | + public boolean isNStraightHand(int[] hand, int groupSize) { |
| 3 | + if (hand.length % groupSize != 0) { |
| 4 | + return false; |
| 5 | + } |
| 6 | + Map<Integer, Integer> map = new HashMap<>(); |
| 7 | + for (int num : hand) { |
| 8 | + map.put(num, map.getOrDefault(num, 0) + 1); |
| 9 | + } |
| 10 | + PriorityQueue<Integer> pq = new PriorityQueue<>(map.keySet()); |
| 11 | + while (!pq.isEmpty()) { |
| 12 | + List<Integer> temp = new ArrayList<>(); |
| 13 | + int prev = -1; |
| 14 | + for (int i = 0; i < groupSize; i++) { |
| 15 | + if (pq.isEmpty()) { |
| 16 | + return false; |
| 17 | + } |
| 18 | + int removed = pq.remove(); |
| 19 | + map.put(removed, map.get(removed) - 1); |
| 20 | + if (map.get(removed) > 0) { |
| 21 | + temp.add(removed); |
| 22 | + } |
| 23 | + if (prev != -1 && removed != prev + 1) { |
| 24 | + return false; |
| 25 | + } |
| 26 | + prev = removed; |
| 27 | + } |
| 28 | + pq.addAll(temp); |
19 | 29 | }
|
20 |
| - counterMap.put(temp, counterMap.get(temp) - 1); |
21 |
| - temp++; |
22 |
| - } |
23 |
| - while (iter.hasNext() && counterMap.get(curr) == 0) { |
24 |
| - curr = iter.next(); |
25 |
| - } |
| 30 | + return true; |
26 | 31 | }
|
27 |
| - return true; |
28 |
| - } |
29 | 32 | }
|
0 commit comments