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

题目连接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/

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

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

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

解题过程:

参考题解

使用Set判重和max - min < 5

题目中 0 是可以变作任何数字的。

所以,形成顺子的充要条件是:

  • 数组中除了0,其它的数字不能重复
  • 数组中除了0,最大值减去最小值的差小于5

因为,当差大于5时,又由于数组中的数不能重复,所以数组中0的个数就不能补齐中间的空白。

class Solution {
    public boolean isStraight(int[] nums) {
        Set<Integer> repeat = new HashSet<>();
        int max = -1, 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;
            repeat.add(num);
        }
        return max - min < 5;
    }
}

剑指 Offer 61.——扑克牌中的顺子_第1张图片

使用排序遍历判重,获取最大值最小值。思路一样

你可能感兴趣的:(LeetCode)