This commit is contained in:
ShusenTang 2020-02-16 20:13:31 +08:00
parent ab3c197611
commit b8596e310e
2 changed files with 37 additions and 0 deletions

View File

@ -299,6 +299,7 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。
| 665 |[Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/665.%20Non-decreasing%20Array.md)|Easy| |
| 714 |[Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/714.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20with%20Transaction%20Fee.md)|Medium| |
| 829 |[Consecutive Numbers Sum](https://leetcode.com/problems/consecutive-numbers-sum/)|[C++](solutions/829.%20Consecutive%20Numbers%20Sum.md)|Hard| |
| 846 |[Hand of Straights](https://leetcode.com/problems/hand-of-straights/)|[C++](solutions/846.%20Hand%20of%20Straights.md)|Medium| |
| 905 |[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|[C++](solutions/905.%20Sort%20Array%20By%20Parity.md)|Easy| |
| 946 |[Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/)|[C++](solutions/946.%20Validate%20Stack%20Sequences.md)|Medium| |
| 1155 |[Number of Dice Rolls With Target Sum](https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/)|[C++](solutions/1155.%20Number%20of%20Dice%20Rolls%20With%20Target%20Sum.md)|Medium| |

View File

@ -0,0 +1,36 @@
# [846. Hand of Straights](https://leetcode.com/problems/hand-of-straights/)
# 思路
这道题说手里有扑克牌若干是否能将手里的牌都以顺子的形式出完每组顺子的牌数都为W。
由于顺子是等差为1的等差数列所以如果知道了最小元素也就知道了其他所有元素。所以我们可以使用贪婪的算法首先取出手中最小的牌再按照不断+1的规则组成第一组顺子再在剩下的牌中按照上一次一样的规则组成第二组顺子以此类推。由此可见我们需要一个快速获得最小值和快速删除元素的数据结构map和multiset满足我们的要求。
若使用map我们可以记录元素值到出现次数的隐射删除操作即将出现次数减1若使用multiset我们每次根据迭代器删除元素即可即`.erase(.find(val))`(不能根据元素值删除`.erase(val)`那样会将所有值相等的元素都删了代码中我们使用multiset。
时间复杂度O(nlogn)空间复杂度O(n)
# C++
```C++
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int W) {
int n = hand.size(), groups = n / W;
if(n % W) return false;
multiset<int>cards;
for(int num: hand) cards.insert(num);
int pre;
while(groups--){
pre = *cards.begin();
cards.erase(cards.begin());
for(int j = 1; j < W; j++){
if(cards.find(++pre) == cards.end()) return false;
cards.erase(cards.find(pre));
}
}
return true;
}
};
```