zoukankan      html  css  js  c++  java
  • #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

  • 相关阅读:
    16 Errors and Exceptions
    13 Asynchronous Programming
    wpf入门
    iframe cross domain
    ini_set("error_log",$error_path)设置
    MySQL中merge表存储引擎用法
    php中静态属性静态方法的用法
    PHP的SESSIONID生成原理
    composer的基本 使用
    相邻省份数组
  • 原文地址:https://www.cnblogs.com/zlrrrr/p/10160771.html
Copyright © 2011-2022 走看看