iT邦幫忙

2024 iThome 鐵人賽

DAY 29
0
自我挑戰組

Leetcode 解題之旅:逐日攻克系列 第 29

每日一LeetCode(29)

  • 分享至 

  • xImage
  •  

846. Hand of Straights

題目敘述:

Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.

Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.


class Solution {
public:
    bool isNStraightHand(std::vector<int>& hand, int groupSize) {
        if (hand.size() % groupSize != 0) {
            return false;
        }

        std::unordered_map<int, int> count;
        for (int card : hand) {
            count[card]++;
        }

        std::vector<int> sortedKeys;
        for (auto& pair : count) {
            sortedKeys.push_back(pair.first);
        }
        std::sort(sortedKeys.begin(), sortedKeys.end());

        for (int key : sortedKeys) {
            if (count[key] > 0) {  
                int startCount = count[key];
                for (int i = key; i < key + groupSize; i++) {
                    if (count[i] < startCount) {
                        return false;
                    }
                    count[i] -= startCount;
                }
            }
        }
        return true;
    }
};

上一篇
每日一LeetCode(28)
下一篇
每日一LeetCode(30)
系列文
Leetcode 解題之旅:逐日攻克30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言