1. 程式人生 > >leetcode 846. Hand of Straights

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]之前的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;
    }
};