[leetcode]846. Hand of Straights
阿新 • • 發佈:2018-11-09
[leetcode]846. Hand of Straights
Analysis
早鴨—— [每天刷題並不難0.0]
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.
看手中的牌能不能都連成長度為W的順子出掉。
Implement
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int W) {
int len = hand.size();
if(len%W != 0)
return false;
sort(hand.begin(), hand.end());
map<int, int> cnt;
for(auto h:hand)
cnt[h]++ ;
for(auto it:cnt){
if(it.second > 0){
for(int i=W-1; i>=0; i--){
cnt[it.first+i] -= cnt[it.first];
if(cnt[it.first+i] < 0)
return false;
}
}
}
return true;
}
};