每日一题-一手好牌(中等)

304 阅读1分钟

846. 一手顺子

一、题目描述

Alice 手中有一把牌,她想要重新排列这些牌,分成若干组,使每一组的牌数都是 groupSize ,并且由 groupSize 张连续的牌组成。

给你一个整数数组 hand 其中 hand[i] 是写在第 i 张牌,和一个整数 groupSize 。如果她可能重新排列这些牌,返回 true ;否则,返回 false 。

二、示例

示例 1:

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

示例 2:

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

提示:

  • 1 <= hand.length <= 104
  • 0 <= hand[i] <= 109
  • 1 <= groupSize <= hand.length

三、分析

为方便,我们记groupSize为g。如题若需手牌hand可分成若干组,且每组大小均为g,牌也必须连续,那么hand.size mod g == 0,否则直接返回false。接下来我们可以采用贪心策略模拟重新洗牌,首先我们用一个哈希表记录hand中每章牌出现的次数,将hand排序后,接着来模拟分组。每次组牌时都采用hand中所剩牌中最小的x,那么这组牌中最大应为 x+g-1,若中间缺失一张,则直接返回false。若每张牌均有,就将哈希表中对应的次数减一。依此直至整个hand遍历结束。

复杂度分析

对hand排序需要O(nlog(n)),遍历hand数组需要O(n),整体的时间复杂度为O(nlog(n))。

四、编码

public class IsNStringHand {
    public boolean isNStraightHand(int[] hand, int groupSize) {
        int len = hand.length;
        if (!(len % groupSize == 0)) {
            return false;
        }
        Arrays.sort(hand);
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i : hand) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        for (int i : hand) {
            if (!map.containsKey(i)) {
                continue;
            }
            for (int j = 0; j < groupSize; j++) {
                int x = i + j;
                if (!map.containsKey(x)) {
                    return false;
                }
                map.put(x, map.get(x) - 1);
                if (map.get(x) == 0) {
                    map.remove(x);
                }
            }
        }

        return true;
    }

}

题目链接