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

    题解:

    Get the smallest number, check if there are next W consecutive numbers.

    Have a TreeMap map to maintain the frequency of each number.

    Every time, get the latest number key in map and its count, for next key + 1, key +2 ... key + W -1, if their frequency < count, then they can't be made as W consecutive cards, return false.

    Otherwise, remove the count from each of their frequency.

    Time Complexity: O(mwlogm). TreeMap, get, put, remove all takes O(logm). m = hand.length.

    Space: O(m).

    AC Java:  

     1 class Solution {
     2     public boolean isNStraightHand(int[] hand, int W) {
     3         TreeMap<Integer, Integer> map = new TreeMap<>();
     4         for(int i : hand){
     5             map.put(i, map.getOrDefault(i, 0)+1);
     6         }
     7         
     8         for(int key : map.keySet()){
     9             int count = map.get(key);
    10             if(count > 0){
    11                 for(int i = key+W-1; i>=key; i--){
    12                     if(map.getOrDefault(i, 0) < count){
    13                         return false;
    14                     }
    15                     
    16                     map.put(i, map.get(i)-count);
    17                 }
    18             }
    19         }
    20         
    21         return true;
    22     }
    23 }
  • 相关阅读:
    mysql解决插入中文数据显示??
    js实现表单联动
    CSS实现圆角,圆角阴影
    图片预加载实例
    响应式开发学习笔记
    关于viewport
    HTML5 中的结构元素
    linux- deppin 下配置xampp的方法(全)
    # XAMPP 配置密码大全修改默认密码
    Jquery 最大高度
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11856487.html
Copyright © 2011-2022 走看看