题目
从扑克牌中随机抽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] .
代码
Python
# 思路:
# 除大小王外,其余牌无重复且最值相差小于5
# 复杂度:
# O(N)
class Solution:
def isStraight(self, nums: List[int]) -> bool:
st=set()
a,b=0,14
for num in nums:
if num==0: continue # 跳过大小王
a=max(a,num) # 最大牌
b=min(b,num) # 最小牌
if num in st: return False
st.add(num)
return a-b<5
C++
class Solution {
public:
bool isStraight(vector<int>& nums) {
set<int> st;
int a=0,b=14;
for (int num:nums) {
if (num==0) continue;
a=max(a,num);
b=min(b,num);
if (st.find(num)!=st.end()) return false;
st.insert(num);
}
return a-b<5;
}
};