1. 程式人生 > >#Leetcode# 846. Hand of Straights

#Leetcode# 846. Hand of Straights

https://leetcode.com/problems/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

程式碼:

class Solution {
public:
    bool isNStraightHand(vector<int>& hand, int W) {
        int n = hand.size();
        map<int, int> mp;
        if(n % W) return false;
        if(W == 1) return true;
        
        sort(hand.begin(), hand.end());
        
for(int i = 0; i < n; i ++) mp[hand[i]] ++; int ans = 0; for(int i = 0; i < n - 1; i ++) { if(mp[hand[i]]) { int temp = hand[i]; mp[temp] --; int cnt = 1; for(int j = i + 1; j < n; j ++) { if(hand[j] - temp == 1 && mp[hand[j]] && cnt < W) { mp[hand[j]] --; cnt ++; temp = hand[j]; } } if(cnt == W) ans ++; } } if(ans == n / W) return true; return false; } };
View Code

我笨拙的 code 這個是在 map 專題裡面的(因為看到 map 這個 tag 裡面題目只有兩個!激起了刷掉的慾望!) 一定是我還沒透徹理解 map 今天杭州和蘇州都在下雨 今天感冒終於見好轉 等 FH 忙完再找 debug 吧!