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 }
  • 相关阅读:
    Web应用程序并发问题处理的一点小经验
    *.pvr.ccz文件还原成png格式
    在python 中is和= = 的区别
    pyhton,数据类型
    python,序列化
    python, 操作文件和目录
    python文件,字符串,二进制的读写
    io编程,python
    python,错误、调试和测试
    python,多线程
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11856487.html
Copyright © 2011-2022 走看看