From b8596e310eacc2e2c43255f0e02c55154f248764 Mon Sep 17 00:00:00 2001 From: ShusenTang Date: Sun, 16 Feb 2020 20:13:31 +0800 Subject: [PATCH] add 846 --- README.md | 1 + solutions/846. Hand of Straights.md | 36 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 solutions/846. Hand of Straights.md diff --git a/README.md b/README.md index 968583a..b065f78 100644 --- a/README.md +++ b/README.md @@ -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| | diff --git a/solutions/846. Hand of Straights.md b/solutions/846. Hand of Straights.md new file mode 100644 index 0000000..29912a0 --- /dev/null +++ b/solutions/846. Hand of Straights.md @@ -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& hand, int W) { + int n = hand.size(), groups = n / W; + if(n % W) return false; + + multisetcards; + 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; + } +}; +``` \ No newline at end of file