【问题描述】[简单]
【解答思路】
1. 集合 Set + 遍历
时间复杂度:O(N) 空间复杂度:O(N)
class Solution {public boolean isStraight(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; // 若有重复,提前返回 falserepeat.add(num); // 添加此牌至 Set}return max - min < 5; // 最大牌 - 最小牌 < 5 则可构成顺子}
}
2. 排序 + 遍历
时间复杂度:O(N) 空间复杂度:O(1)
class Solution {public boolean isStraight(int[] nums) {int joker = 0;Arrays.sort(nums); // 数组排序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 则可构成顺子}
}
public class isStraight {public boolean isStraight(int[] nums) {Arrays.sort(nums);int countZero = 0, i = 0, gap = 0;for (; i < 5 && nums[i] == 0; i++)countZero++;for (i = i + 1; i < 5; i++) {if (nums[i] == nums[i - 1])return false;if (nums[i] - nums[i - 1] > 1)gap += nums[i] - nums[i - 1] - 1;}return countZero >= gap;}
}
【总结】
1.连续数组问题 HashSet/找规律 遍历
2.头尾相减 相邻相减 找找规律
转载链接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/solution/61java-pai-xu-tong-ji-0he-kong-que-de-ge-shu-xiang/
转载链接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/solution/mian-shi-ti-61-bu-ke-pai-zhong-de-shun-zi-ji-he-se/