Alice has a hand
of cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is size W
, and consists of W
consecutive cards.
Return true
if and only if she can.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 Output: true Explanation: Alice'shand
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
==============================================================
Ideas:
For continuous numbers, like {1,2,3,3,3,4,4,5,5,5,6} W=3 ,I choose to use a queue to store each number as the number of 'shunzi' beginning, so that I can calculate the minimum number of 'shunzi' next number, and the answer that does not meet the requirements can be ruled out.
==============================================================
Code:
class Solution {
private LinkedList<Integer> record = new LinkedList<>();
private int group = 0;
public boolean isNStraightHand(int[] hand, int W) {
if(hand.length%W!=0) {
return false;
}
if (W==1) return true;
Arrays.sort(hand);
group = W;
int pre = hand[0];
int count = 1;
int minNeed = 0;
for (int i = 1; i < hand.length; i++) {
if (pre == hand[i]){
count++;
}else {
if (minNeed>count){
return false;
}else{
record.offer(count-minNeed);
}
minNeed = count - getNew();
if (minNeed == 0){
record = new LinkedList<>();
}else if (minNeed<0){
return false;
}else if(pre+1!=hand[i]){
return false;
}
count = 1;
pre = hand[i];
}
}
return count == minNeed;
}
private int getNew(){
if (group==record.size()){
return record.poll();
}else {
return 0;
}
}
}