赌神
Description
你手中有一把牌,需要重新排列这些牌,分成若干组,使每一组的牌数都是groupSize,并且由groupSize张连续的牌组成。
给你一个整数数组hand,其中hand[i]是写在第i张牌上的数值。如果你可以重新排列这些牌,返回true;否则,返回false。
Input
第一行输入数组元素hand[i],用“,”隔开
第二行输入数字groupSize
1≤hand.length≤10
0≤hand[i]≤10^6
1≤groupSize≤hand.length
Output
输出true或者false。
Sample
代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s[] = in.nextLine().replace(" ","").split(",");
int array[] = new int[s.length];
for(int i = 0;i<s.length;i++) {
array[i] = Integer.valueOf(s[i]);
}
int groupSize = in.nextInt();
if(isNStraightHand(array,groupSize)){
System.out.println("true");
}else System.out.println("false");
}
public static 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.getOrDefault(card,0)找到该元素的值,如果没有就返回0
map.put(card,map.getOrDefault(card,0)+1);
heap.offer(card);
}
while(!heap.isEmpty()){
int start=heap.peek();
//寻找后续数字,能否形成顺子
for(int j=0;j<groupSize;j++){
if(!map.containsKey(start+j)){
return false;
}else{
heap.remove(start+j);
int num=map.get(start+j);
if(num-1==0){
map.remove(start+j);
}else{
//重新覆盖
map.put(start+j,num-1);
}
}
}
}
return true;
}
}
思路
使用PriorityQueue和HashMap进行数据存储以及处理,优先队列能够自动排序,HashMap存储key的数量,即value