[leetcode]846. Hand of Straights

[leetcode]846. Hand of Straights


Analysis

早鸭—— [每天刷题并不难0.0]

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.
在这里插入图片描述
看手中的牌能不能都连成长度为W的顺子出掉。

Implement

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;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/83444068