846 Hand of Straights
846. Hand of Straights
1. Question
Alice has ahandof cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is sizeW, and consists ofWconsecutive cards.
Returntrueif 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 <= hand.length <= 100000 <= hand[i] <= 10^91 <= W <= hand.length
2. Implementation
(1) Bucket Sort
思路: Bucket Sort的思路并不是很懂
(2) TreeMap
思路: 将card放在TreeMap中,key是card的值,value是card的个数。然后我们从最小的card开始,遍历card到card + W, 如果其中有张card不在map里,说明不能形成一个size为W的straight,return false.否则,更新card在map中的数量
3. Time & Space Complexity
Bucket Sort:时间复杂度O(), 空间复杂度O()
TreeMap: 时间复杂度O(WlogN), N为card的数量, W是straight的size, 空间复杂度O(N)
Last updated
Was this helpful?