[leetcode] 846. Hand of Straights

441 篇文章 0 订阅
284 篇文章 0 订阅

Description

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

分析

题目的意思是:给你一个卡片数组,和W。现在问能不能把卡片数组分为W个小数组,每个小数组都是等差数列,每个小数组里有W个数。

  • 如果数组的大小n不是W的整数倍,则直接返回false。
  • 这道题用hashmap来解决,先统计每个数的频率,遍历hash表,每次减去m[it.first]就行了,等于减去W序列中第一个值的count,这个解法很妙,我想不到。
  • 注意:map内部本身就是按序存储的(比如红黑树)。在我们插入<key, value>键值对时,就会按照key的大小顺序进行存储。

我们看看其中一个例子的运算过程:
hand = [1,2,3,6,2,3,4,7,8], W = 3
m 1:1 2:2 3:2 4:1 6:1 7:1 8:1
第一次循环:m 1:0 2:1 3:1 4:1 6:1 7:1 8:1
第二次循环:m 1:0 2:0 3:0 4:0 6:1 7:1 8:1
第三次循环:m 1:0 2:0 3:0 4:0 6:0 7:0 8:0
返回true

代码

class Solution {
public:
    bool isNStraightHand(vector<int>& hand, int W) {
        int n=hand.size();
        if(n%W!=0) return false;
        map<int,int> m;
        for(int num:hand){
            m[num]++;
        }
        for(auto it:m){
            if(m[it.first]>0){
                for(int i=W-1;i>=0;i--){
                    if((m[it.first+i]-=m[it.first])<0){
                        return false;
                    }
                }
            }
        }
        return true;
    }
};

参考文献

846. Hand of Straights

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值