Problem
题目大意:给你一些牌,问你能否分组,要求每组w张连续的牌。
https://leetcode.com/problems/hand-of-straights/description/
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
Solution: Greedy
Time complexity: O(nlogn)
Space complexity: O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua // Running time: 65 ms class Solution { public: bool isNStraightHand(vector<int>& hand, int W) { map<int, int> counts; for (int h : hand) ++counts[h]; while (!counts.empty()) { auto it = counts.begin(); int start = it->first; for (int j = 0; j < W; ++j) { if (it == counts.end() || it->first != start + j) return false; auto prev = it++; if (--(prev->second) == 0) counts.erase(prev); } } return true; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment