Alice has ahand
of cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is sizeW
, and consists ofW
consecutive cards.
Returntrue
if and only if she can.
Input:
hand = [1,2,3,6,2,3,4,7,8], W = 3
Output:
true
Explanation:
Alice's
hand
can be rearranged as
[1,2,3],[2,3,4],[6,7,8]
.
Example 2:
Input:
hand = [1,2,3,4,5], W = 4
Output:
false
Explanation:
Alice's
hand
can't be rearranged into groups of
4
.
Note:
1
<
= hand.length
<
= 10000
0
<
= hand[i]
<
= 10^9
1
<
= W
<
= hand.length
class Solution {
public boolean isNStraightHand(int[] hand, int W) {
if (hand == null || hand.length == 0) return false;
int n = hand.length;
if (n < W || n % W != 0) return false;
PriorityQueue<Integer> pq = new PriorityQueue<>();
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < n; i++){
pq.offer(hand[i]);
hash.put(hand[i], hash.getOrDefault(hand[i], 0) + 1);
}
while (!pq.isEmpty()){
int last = pq.poll();
hash.put(last, hash.get(last) - 1);
if (hash.get(last) > 0) pq.offer(last);
for (int i = 1; i < W; i++){
int cur = last + 1;
pq.remove(cur);
if (!hash.containsKey(cur)) return false;
last = cur;
hash.put(cur, hash.get(cur) - 1);
if (hash.get(cur) > 0) pq.offer(cur);
//System.out.println("last: " + last + " cur: " + cur + " i: " + i + " count: " + hash.get(cur));
}
}
return true;
}
}