Hand of Straights

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

题目理解:

给定一个数组nums,和整数W,问是否能将nums分为若干子数组,且每组含有W个数字,并且这W个数字是连续的

解题思路:

首先我们可以想到,中间的数字可能会有比较复杂的分组可能,但是数组中最小的数一定是某一个子数组的第一个数字,而且数组中一定要含有从这个数字往后的W-1个数字,所以我们首先将数组进行排序,然后从小到大遍历,这样我们每次就可以知道一每一个数字应该放在什么地方。

我们用记号[num, count]表示num这个数字是我接下在需要的,而且,这个子数组中还需要count个数字,当我们遇到num后,这个记号变为[num+1, count - 1],直到count变为0。在遍历数组的时候,我们会有一系列的记号[num, count],如果我当前遍历的数字是我需要的某一个num,则将记号做前述修改,否则,加入新的记号[num, W - 1]。

在具体实现上,可以使用map,key是我需要的数字num,value是与num相关的所有count的集合

class Solution {
    public boolean isNStraightHand(int[] hand, int W) {
        if(W == 1)
    		return true;
    	if(hand.length % W != 0)
    		return false;
    	Map<Integer, Queue<Integer>> map = new HashMap<Integer, Queue<Integer>>();
    	Arrays.sort(hand);
    	for(int num : hand) {    		
    		if(!map.containsKey(num))
    			map.put(num, new LinkedList<Integer>());
    		Queue<Integer> cur = map.get(num);
    		if(cur.size() == 0) {
    			if(!map.containsKey(num + 1))
        			map.put(num + 1, new LinkedList<Integer>());
    			map.get(num + 1).offer(W - 1);
    		}
    		else {
    			int ct = cur.poll();
    			ct--;
    			if(ct > 0) {
    				if(!map.containsKey(num + 1))
            			map.put(num + 1, new LinkedList<Integer>());
    				map.get(num + 1).offer(ct);
    			}
    		}

    	}
    	for(int key : map.keySet()) {
    		//System.out.println(key + " : " + map.get(key).toString());
    		if(map.get(key).size() > 0)
    			return false;
    	}
    	return true;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_37889928/article/details/82962014
今日推荐