一手顺子

2020-06-20  本文已影响0人  Stack1_e27c

爱丽丝有一手(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 的组。

class Solution {
    public boolean isNStraightHand(int[] hand, int W) {
        if(hand==null||hand.length==0||hand.length%W!=0)
        {
            return false;
        }

        TreeMap<Integer, Integer> count = new TreeMap<Integer, Integer>();
        for(int c:hand)
        {
            if(!count.containsKey(c))
            {
                count.put(c, 1);
            }else{
                count.replace(c, count.get(c)+1);
            }
        }

        while(count.size()>0)
        {
            int first = count.firstKey();
            for(int i=first;i<first+W;++i)
            {
                if(!count.containsKey(i))
                {
                    return false;
                }
                int c = count.get(i);
                if(c==1){
                    count.remove(i);
                }else{
                    count.replace(i, count.get(i)-1);
                }
            }
        }
        return true;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读