剑指 Offer 61. 扑克牌中的顺子

题目描述

从扑克牌中随机抽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] .

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof

思路解析

5张牌能否组成顺子,需要满足以下条件:

  • 除0外其余数字不能重复
  • 最大值与最小值之差小于等于4

使用set,依次插入非零元素,判断set的元素个数与零元素个数之和是否为5。

代码实现

class Solution {
public:
    bool isStraight(vector<int>& nums) {
        int zero_num = 0;
        int max = 0;
        int min = 13;
        set<int> pokers;
        for(auto nt : nums) {
            if(nt) {
                pokers.insert(nt);
                max = (max > nt) ? max : nt;
                min = (min < nt) ? min : nt;
            }
            else
                zero_num++;
        }
        if(pokers.size() != nums.size() - zero_num)
            return false;
        if(max - min > 4)
            return false;
        return true;
    }
};
原文地址:https://www.cnblogs.com/xqmeng/p/13680662.html