categories: [Blog,Algorithm]


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

难度简单98
从扑克牌中随机抽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. class Solution {
  2. public boolean isStraight(int[] nums) {
  3. Set<Integer> repeat = new HashSet<>();
  4. int max = 0, min = 14;
  5. for(int num : nums) {
  6. if(num == 0) continue; // 跳过大小王
  7. max = Math.max(max, num); // 最大牌
  8. min = Math.min(min, num); // 最小牌
  9. if(repeat.contains(num)) return false; // 若有重复,提前返回 false
  10. repeat.add(num); // 添加此牌至 Set
  11. }
  12. return max - min < 5;// 最大牌 - 最小牌 < 5 则可构成顺子
  13. //&& max - min >=2; // max - min >=2 加不加 都可以
  14. }
  15. // 作者:jyd
  16. // 链接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/solution/mian-shi-ti-61-bu-ke-pai-zhong-de-shun-zi-ji-he-se/
  17. }

解析
image.png