zoukankan      html  css  js  c++  java
  • LC 846. Hand of Straights

    Alice has 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 Wconsecutive 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

    Runtime: 80 ms, faster than 24.90% of C++ online submissions for Hand of Straights.

    我的思路很直接,用map保存。

    class Solution {
    public:
      bool isNStraightHand(vector<int>& hand, int W) {
            int n = hand.size();
            if (n < 1 || W < 1 || n < W)
            {
                return false;
            }
           
            if (n % W != 0)
            {
                return false;
            }
        map<int,int> mp;
        for(auto x : hand) mp[x]++;
        for(auto it : mp){
          if(it.second == 0) continue;
          int cntit = it.second;
          for(int i=1; i<W;i++){
            if(!mp.count(it.first) || mp[it.first+i] < mp[it.first]) return false;
            mp[it.first+i] -= mp[it.first];
          }
          mp[it.first] = 0;
        }
        for(auto it : mp){
          if(it.second != 0) return false;
        }
        return true;
      }
    };

    网上看到一个比较好的思路是,把所有的数%W,因为是连续的,所以一个连续的W个数modW后必定在0 ~ W-1 中是连续存在的,妙。

    class Solution {
    public:
        bool isNStraightHand(vector<int>& hand, int W) {
            int n = hand.size();
            if (n < 1 || W < 1 || n < W)
            {
                return false;
            }
           
            if (n % W != 0)
            {
                return false;
            }
            
            vector<int> count (W, 0);
            for (const int& h : hand)
            {
                ++count[h % W];
            }
            
            int expect = count.front();
            for(const int& c : count)
            {
                if (c != expect)
                {
                    return false;
                }
            }
            
            return true;
        }
    };
  • 相关阅读:
    API网关服务
    技术攻关:从零到精通 https://mp.weixin.qq.com/s/mix-0Ft9G1F5yddNjSzkrw
    如何在团队中推广一项技术 —— 解决Odin一站式微前端的缓存问题
    设计模式的底层逻辑 找到变化,封装变化
    从Android内存到图片缓存优化
    百度C++工程师的那些极限优化(内存篇)
    享元模式
    协同编辑冲突处理算法综述
    大型前端项目内存优化总结
    雪碧图
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10179315.html
Copyright © 2011-2022 走看看