Featured image of post 剑指 Offer 61. 扑克牌中的顺子

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

解法一:排序

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
func isStraight(nums []int) bool {
    sort.Ints(nums)
    i := 0
    for nums[i] == 0 {
        i++
    }
    cnt := i + 1
    for i+1 < len(nums) {
        diff := nums[i+1] - nums[i]
        if diff == 0 {
            return false
        } else if diff > 1 {
            if diff > cnt {
                return false
            }
            cnt -= diff
        }
        i++
    }
    return true
}

解法二:哈希表

Licensed under CC BY-NC-SA 4.0
最后更新于 2023/06/23 19:50:58
comments powered by Disqus
Built with Hugo
主题 StackJimmy 设计