连续5张牌,有个规律就是有重复数字的必然不是5张牌,最大值-最小值<=4的才是连续的5张牌
第一种方式:
class Solution {
public boolean isStraight(int[] nums) {
//如果是连续的5张牌,最大值-最小值<=4,并且不能有重复的数字
//方法一:通过set的方式进行判重,
//方法二:通过数组排序,对是0的数字进行去重,然后从第2个字符开始
int max = 0,min=13;
HashSet<Integer> HashSet = new HashSet<>();
for(int i=0;i<nums.length;i++){
if(nums[i]==0) continue;
if(HashSet.contains(nums[i])) return false;
HashSet.add(nums[i]);
max = Math.max(max,nums[i]);
min = Math.min(min,nums[i]);
}
return max-min<=4;
}
}
算法二:也是对两个进行去重,去重的算法就是将数组进行排序,然后对相邻两个的值,进行判==,如果相等的话,就退出
class Solution {
public boolean isStraight(int[] nums) {
Arrays.sort(nums);
int max = 0,min=13;
int count = 0;
for(int i =0;i<nums.length-1;i++){
if(nums[i]==0){
continue;
}
if(nums[i+1]==nums[i]){
return false;
}
max=Math.max(max,nums[i]);
min = Math.min(min,nums[i]);
}
max=Math.max(max,nums[nums.length-1]);
return max-min<=4;
}
}
解法2:由于利用数组是拍过序的,所以每次就没有必要跟数组计算最大值和最小值,最大值就是最后一个值,最小值,就是抛出0的,那个位置的值
class Solution {
public boolean isStraight(int[] nums) {
Arrays.sort(nums);
int max = 0,min=13;
int count = 0;
for(int i =0;i<nums.length-1;i++){
if(nums[i]==0){
count++;
continue;
}
if(nums[i+1]==nums[i]){
return false;
}
}
return nums[nums.length-1]-nums[count]<=4;
}
}