LeetCode Hand of Straights

本文介绍了一种算法,用于判断一副给定的牌是否能被重新排列成若干个长度为W的连续顺子。通过使用TreeMap存储每张牌及其出现次数,并结合ArrayList辅助判断,实现了一种高效解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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's hand 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. 1 <= hand.length <= 10000
  2. 0 <= hand[i] <= 10^9
  3. 1 <= W <= hand.length

爱丽丝有一手(hand)由整数数组给定的牌。 

现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。

如果她可以完成分组就返回 true,否则返回 false

 

示例 1:

输入:hand = [1,2,3,6,2,3,4,7,8], W = 3
输出:true
解释:爱丽丝的手牌可以被重新排列为 [1,2,3],[2,3,4],[6,7,8]

示例 2:

输入:hand = [1,2,3,4,5], W = 4
输出:false
解释:爱丽丝的手牌无法被重新排列成几个大小为 4 的组。

题解:给定一个数组,表示的是给的一副牌,其中有连续的和不连续之分。现在给定一个W值,验证是否在给定的一副牌中,存在以W为个数的连续的一队顺子,如果存在,那么就返回true;否则返回false。

这道题考虑用到两个数据结构map和list。其中list来存储给定数组中的元素,并且经过过滤了的;map用来存储给定元素及其出现的次数。首先,扫描一遍数组,将list和map填满,之后用Collections.sort(list)对list进行从小到大排序。排完序后,对list进行遍历,以W为每个顺子的大小,每次如果某个元素,可以组成顺子,那么就将该元素在map中的出现的次数减1;如果出现某个顺子的某个元素的次数为0,那么直接返回false。遍历完成后,即可判断是否该数组可以组成长度为W的顺子对。

public boolean isNStraightHand(int[] hand,int W)
	{
		int length = hand.length;
		if(length % W != 0)
			return false;
		ArrayList<Integer> list = new ArrayList<>();
		TreeMap<Integer,Integer> treeMap = new TreeMap<>();
		for(int temp : hand)
		{
			if(!treeMap.containsKey(temp))
			{
				list.add(temp);
				treeMap.put(temp,1);
			}
			else
				treeMap.put(temp,treeMap.get(temp) + 1);
		}
        Collections.sort(list);
		int i = 0;
		while(i < list.size())
		{
			int tmp = list.get(i);
			int offset = 0;
			while(offset < W)
			{
				Integer num = treeMap.get(tmp + offset);
				if(num == null || num < 1)
					return false;
				treeMap.put(tmp + offset,num - 1);
				offset++;
			}
			while(i < list.size() && treeMap.get(list.get(i)) == 0)
				i++;
		}
		return true;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值