扑克牌中的顺子
题目描述
从扑克牌中随机抽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] .
解法:
先排序,然后统计王的个数,以及其他牌中空位个数。比如 1 2 3 4
没有空位,1 2 4 5
缺少 3 才构成顺序,空位为 1。最后判断王是否能够填充空位。
class Solution {
public:
bool isStraight(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n_joker = 0, n_slot = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i] == 0){
n_joker += 1;
continue;
}
if(i > 0 && nums[i] == nums[i-1]){
return false;
}
if(i > 0 && nums[i-1] != 0){
n_slot += nums[i] - nums[i-1] - 1;
}
}
return n_joker >= n_slot;
}
};