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

150 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第13天,点击查看活动详情

Leetcode : leetcode-cn.com/problems/bu…

GitHub : github.com/nateshao/le…

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

Go

func isStraight(nums []int) bool {
   sort.Ints(nums)
   joker:=0
   for i:=0;i<4;i++{
       if nums[i]==0{
           joker++ //记录joker数量
       } else {
           if nums[i]==nums[i+1]{  //除了0之外,有相同的元素直接返回false
               return false
           }
       }
   }
   return nums[4]-nums[joker]<5  
}

方法一:排序 + 遍历

  1. 先对数组执行排序。
  2. 判别重复: 排序数组中的相同元素位置相邻,因此可通过遍历数组,判断 nums[i] = nums[i + 1]是否成立来判重。
  3. 获取最大 / 最小的牌: 排序后,数组末位元素 nums[4] 为最大牌;元素 nums[joker]为最小牌,其中 joker 为大小王的数量。

复杂度分析:

  • 时间复杂度O(NlogN)= O(5log5)=O(1) :中N为nums长度,本题中N=5 ;数组排序使用 O(N log N)时间。
  • 空间复杂度0(1) :变量joker使用O(1)大小的额外空间。

 package com.nateshao.sword_offer.topic_48_isStraight;
 ​
 import java.util.Arrays;
 ​
 /**
  * @date Created by 邵桐杰 on 2022/2/21 22:45
  * @微信公众号 千羽的编程时光
  * @个人网站 www.nateshao.cn
  * @博客 https://nateshao.gitee.io
  * @GitHub https://github.com/nateshao
  * @Gitee https://gitee.com/nateshao
  * Description:
  */
 public class Solution {
     public static void main(String[] args) {
         int[] nums = {1,2,3,4,5};
         System.out.println("isStraight(nums) = " + isStraight(nums));
     }
     public static boolean isStraight(int[] nums) {
         Arrays.sort(nums);
         int joker = 0;
         for (int i = 0; i < 4; i++) {
             if (nums[i]==0)joker++;//统计大小王的数量
             else if(nums[i]==nums[i+1])return false;//重复就返回false
         }
         return nums[4]-nums[joker]<5;//最大牌 - 最小牌 < 5 则可构成顺子
     }
 }
 ​

方法二:集合 Set + 遍历

思路:

  1. 遍历五张牌,遇到大小王(即0)直接跳过。
  2. 判别重复:利用Set实现遍历判重, Set的查找方法的时间复杂度为O(1) ;
  3. 获取最大1最小的牌:借助辅助变量max和min,遍历统计即可。

复杂度分析:

  • 时间复杂度O(N)= O(5)=O(1) :中N为nums长度,本题中N =5 ;遍历数组使用O(N)时间。
  • 空间复杂度O(N)= O(5)=O(1) :用于判重的辅助Set使佣O(N)额外空间。

     public static boolean isStraight2(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 则可构成顺子
     }

参考链接:leetcode-cn.com/problems/bu…

\