Skip to content

[剑指 Offer] 61. 扑克牌中的顺子 #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Aug 20, 2021 · 0 comments
Open

[剑指 Offer] 61. 扑克牌中的顺子 #86

frdmu opened this issue Aug 20, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Aug 20, 2021

从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。

 

示例 1:

输入: [1,2,3,4,5]
输出: True

示例 2:

输入: [0,0,1,2,5]
输出: True

限制:

  • 数组长度为 5 
  • 数组的数取值为 [0, 13] .

解法:
顺子的充分必要条件是:

  • 没有重复的牌
  • 最大值和最小值之间的差小于5
    代码如下:
class Solution {
public:
    bool isStraight(vector<int>& nums) {
        unordered_set<int> repeat;
        int ma = -1, mi = INT_MAX;
        for (auto n: nums) {
            if (n != 0) {
                if (n > ma)
                    ma = n;
                if (n < mi)
                    mi = n;
                if (repeat.count(n) != 0)
                    return false;
                else
                    repeat.insert(n);             
            }
        }

        if (ma - mi < 5)
            return true;
        return false;    
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant