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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public boolean checkDynasty(int[] places) {
Set<Integer> set = new HashSet<>();
int min = 13, max = 0;
for (int place : places) {
if (place != 0) {
if (!set.add(place)) {
// 数字重复,必然无法组成
return false;
}
min = Math.min(min, place);
max = Math.max(max, place);
}
}

return max - min + 1 <= 5;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public boolean checkDynasty(int[] places) {
Arrays.sort(places);

int minIndex = 0; // 指向首个非 0 的元素
for (int i = 0; i < places.length - 1; i++) { // 注意未遍历最后一个元素
if (places[i] == 0) {
minIndex++;
} else if (places[i] == places[i + 1]) {
return false;
}
}

return places[4] - places[minIndex] + 1 <= 5;
}
}

两个关键点:一是不能含有重复的非 0 数字,二是除 0 之外的最大值与最小值的差值不能超过 5。

References

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