码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 846. Hand of Straights

时间:2019-11-14 13:45:12      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:for   exp   lse   card   its   cut   nsis   note   space   

原题链接在这里: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 }

 

LeetCode 846. Hand of Straights

标签:for   exp   lse   card   its   cut   nsis   note   space   

原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11856487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!