题解 | #扑克牌顺子#
扑克牌顺子
http://www.nowcoder.com/practice/762836f4d43d43ca9deb273b3de8e1f4
遍历 + 哈希表
1、此题的关键是把判断是否连续转换成:
- 除大小王外无重复;
- 五张牌中max-min<5。
2、判断重复可以用哈希表或者数组手动记录,判断最大减最小可以排序或者遍历时手动记录最值。
- 因为最小值在有大小王时一定为0,所以要记录除了大小王之外的最小值。当排序时,需要记录joker的数量,这样即可快速找到最小值。
import java.util.*;
public class Solution {
public boolean IsContinuous(int [] numbers) {
Set<Integer> set = new HashSet<>();
int max = 0, min = 14;
for(int num : numbers) {
if(num == 0) {
continue;
}
max = Math.max(max, num);
min = Math.min(min, num);
if(set.contains(num)) {
return false;
}
set.add(num);
}
return max - min < 5;
}
}
排序 + 遍历
import java.util.Arrays;
public class Solution {
public boolean IsContinuous(int [] numbers) {
int joker = 0;
Arrays.sort(numbers);
for(int i = 0; i < 4; i++) {
if(numbers[i] == 0) {
joker++;
} else if(numbers[i] == numbers[i + 1]) {
return false;
}
}
return numbers[4] - numbers[joker] < 5;
}
}
