LeetCode 846. Hand of Straights
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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‘shand
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‘shand
can‘t be rearranged into groups of4
.
Note:
1 <= hand.length <= 10000
0 <= hand[i] <= 10^9
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的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 846 一手顺子[Map 排序] HERODING的LeetCode之路
LeetCode 846 一手顺子[Map 排序] HERODING的LeetCode之路
leetcode1344. Angle Between Hands of a Clock