算法Day20 赌神

赌神

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

  • 18
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值