leetcode 846. Hand of Straights

leetcode 846. 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

解法:

这个题大致意思是让我们判断能否在给定序列中找到 hand.size() / W个长度为 W 的连续递增序列。

  • 首先,我们可以判断 hand.size() % W是否成立,因为任意一个不满足 W 个的序列都不满足题意

  • 其次,我们就要考虑怎么凑成连续的序列:

    • 这里我们可以考虑使用map映射的方法,举个例子:

      • 假如现在序列为example 1 ,也即hand = [1,2,3,6,2,3,4,7,8],那么

        • map[1] = 1;
        • map[2] = 2;
        • map[3] = 2;
        • map[4] = 1;
        • map[6] = 1;
        • map[7] = 1;
        • map[8] = 1;
      • 我们现在可以这么思考,如果序列连续,那么任意一个开始点 start 往后数W-1个连续数字的map值一定满足:
        m a p [ s t a r t + W − 1 ] &gt; = m a p [ s t a r t + W − 2 ] &gt; = . . . . . . m a p [ s t a r t ] map[start + W - 1] &gt;= map[start + W - 2] &gt;= ...... map[start] map[start+W1]>=map[start+W2]>=......map[start]

      • 且每一次我们处理完相应的序列之后,都要让的map[start]之前的map[start + W - N]的值减去map[start],这表明我们已经访问过某个序列。如果在处理过程中有某个map[start + W - N] < 0,那证明序列出现了中断,也就不满足题意。


代码:
class Solution {
public:
    bool isNStraightHand(vector<int>& hand, int W) {
        int len = hand.size();
        if(len%W != 0)
            return false;
        sort(hand.begin(), hand.end());
        map<int, int> cnt;
        for(auto h:hand)
            cnt[h]++;
        for(auto it:cnt){
            if(it.second > 0){
                for(int i=W-1; i>=0; i--){
                    cnt[it.first+i] -= cnt[it.first];
                    if(cnt[it.first+i] < 0)
                        return false;
                }
            }
        }
        return true;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值