剑指 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] .

题目分析

[11,0,9,0,0] 需要明白大小王可以有多个,而且大小王数量>=最大值-最小值的差值。并不一定相等。

在这里插入图片描述

我的思路,先排序,统计大小王数量,遍历找出差值例如对于数组[0,0,1,2,5],统计出大小王为2个,差值为2-1-1 + 5-2-1 = 2;所以输出true,

class Solution {
    public boolean isStraight(int[] nums) {
        Arrays.sort(nums);
        int i = 0;
        while(i<nums.length){
            if(nums[i]!=0){
                break;
            }
            i++;
        }
        int count = 0;
        int j = i;
        while(j<nums.length - 1){
            if(nums[j+1] == nums[j]){
                return false;
            }
            count+=nums[j+1] - nums[j] - 1;
            j++;
        }
        if(count <= i){
            return true;
        }
        return false;
    }
}

用一次for或者while可以增加代码可读性。

class Solution {
    public boolean isStraight(int[] nums) {
    	//大小王数量
        int joker = 0;
        Arrays.sort(nums); // 数组排序
        //中间的差值。类似1,2,5差值为2,即查了一个3,4。
        int count = 0;
        for(int i = 0; i < 4; i++) {
            if(nums[i] == 0) joker++; // 统计大小王数量
            else if(nums[i] == nums[i + 1]) {
                return false;
            }
            else{
                count+=nums[i+1] - nums[i] - 1;
            } // 若有重复,提前返回 false
        }
        return count<=joker; 
        //return nums[4] - nums[joker] < 5;//可以这样子判断, 最大牌 - 最小牌 < 5 则可构成顺子
    }
}

记住,能用set去重尽量用set

class Solution {
    public boolean isStraight(int[] nums) {
        Set<Integer> repeat = new HashSet<>();
        int max = 0, min = 14;
        for(int num : nums) {
            if(num == 0) continue; // 跳过大小王
            max = Math.max(max, num); // 最大牌
            min = Math.min(min, num); // 最小牌
            if(repeat.contains(num)) return false; // 若有重复,提前返回 false
            repeat.add(num); // 添加此牌至 Set
        }
        return max - min < 5; // 最大牌 - 最小牌 < 5 则可构成顺子
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值