LeetCode Hand of Straights

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sun_wangdong/article/details/82657084

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;
	}

猜你喜欢

转载自blog.csdn.net/sun_wangdong/article/details/82657084