Alice 手中有一把牌,她想要重新排列这些牌,分成若干组,使每一组的牌数都是 groupSize ,并且由 groupSize 张连续的牌组成。
给你一个整数数组 hand 其中 hand[i] 是写在第 i 张牌,和一个整数 groupSize 。如果她可能重新排列这些牌,返回 true ;否则,返回 false 。
其实思路还是挺简单的,就是哈希表统计每个数字出现次数,每轮选取当前还没用完的最小数字(考虑使用最小堆),逐个往后遍历groupSize个数字,如果map中找不到自然就要返回false,如果为零就要从map中移除,一个小关键点在于,堆中取出的开始元素也要确定map中有没有,没有就不能从这个数字开始寻找
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if(groupSize==1){
return true;
}
int n=hand.length;
PriorityQueue<Integer>heap=new PriorityQueue<>();
HashMap<Integer,Integer>map=new HashMap<>();
if(n%groupSize!=0){
return false;
}
//数据初始化记录
for(int card:hand){
map.put(card,map.getOrDefault(card,0)+1);
heap.offer(card);
}
while(!heap.isEmpty()){
int start=heap.poll();
//开始数字,要确保map中有记录
if(!map.containsKey(start))continue;
//寻找后续数字,能否形成顺子
for(int j=0;j<groupSize;j++){
if(!map.containsKey(start+j)){
return false;
}else{
int num=map.get(start+j);
if(num-1==0){
map.remove(start+j);
}else{
map.put(start+j,num-1);
}
}
}
}
return true;
}
}