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 Wconsecutive 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'shandcan 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 <= 100000 <= hand[i] <= 10^91 <= 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;
}
}
}
本文介绍了一种手牌分组算法,旨在将一组整数形式的手牌重新排列为大小为W的连续数字组。通过使用队列记录每种数字作为顺子开始的数量,算法能够计算下一个数字所需的最少顺子数量,从而排除不符合要求的答案。
1147

被折叠的 条评论
为什么被折叠?



