目录结构
1.题目
从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。
示例:
输入: [1,2,3,4,5]
输出: True
输入: [0,0,1,2,5]
输出: True
限制:
- 数组长度为 5
- 数组的数取值为 [0, 13] .
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
只有除大小王外的牌不重复且【最大值-最小值】小于5才能构成顺子。
public class Offer61 {
@Test
public void test() {
int[] nums = {0, 0, 1, 2, 3};
System.out.println(isStraight(nums));
}
public boolean isStraight(int[] nums) {
Set<Integer> repeat = new HashSet<>();
int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
for (int i = 0; i < 5; i++) {
if (nums[i] != 0) {
max = Math.max(max, nums[i]);
min = Math.min(min, nums[i]);
if (repeat.contains(nums[i])) {
return false;
} else {
repeat.add(nums[i]);
}
}
}
return max - min < 5;
}
}
- 时间复杂度:
- 空间复杂度: