剑指 Offer 61. 扑克牌中的顺子
题目:
从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。
示例 1:
输入: [1,2,3,4,5] 输出: True
示例 2:
输入: [0,0,1,2,5] 输出: True
限制:
数组长度为 5
数组的数取值为 [0, 13] .
代码:
采用穷举法把每种情况都考虑出来,if else 一直列出来
1 class Solution { 2 public boolean isStraight(int[] nums) { 3 //先排序,这样比较好计算 4 Arrays.sort(nums); 5 int count0=0; 6 7 for (int i = 0; i <nums.length ; i++) { 8 //统计万能数字 9 if(nums[i]==0){ 10 count0++; 11 continue; 12 } 13 14 //不是第一位的前一位为0,此下标位必然没有问题,如果是第一位必然没有问题 15 if(i>0&&nums[i-1]!=0){ 16 //存在对子,false 17 if(nums[i]-nums[i-1]==0){return false;} 18 //两个数中间空的数字比万能数字大,false 19 if(nums[i]-nums[i-1]-1>count0){ 20 return false; 21 //连续数字,继续遍历下一位 22 }else if(nums[i]-nums[i-1]==1){ 23 continue; 24 }else{ 25 //非连续,且空的数字小于或等于万能数字 26 int val=nums[i]-nums[i-1]-1; 27 count0-=val; 28 //万能数字少于0,倒欠,必然不可能存在顺子 29 } 30 } 31 } 32 return true; 33 } 34 }
代码2:
1 //这个思路是题解中的:两个方向,有对子,或非零的最大值和最小值差大于4,都不可能存在顺子 2 class Solution { 3 public boolean isStraight(int[] nums) { 4 //先排序,这样比较好计算 5 Arrays.sort(nums); 6 int count0=0; 7 int min=14; 8 int max=0; 9 //记录对子 10 Set<Integer> set=new HashSet<>(); 11 for (int i = 0; i <nums.length ; i++) { 12 if(nums[i]!=0&&set.contains(nums[i])){ 13 return false; 14 } 15 //统计非零最大值和最小值 16 if(nums[i]!=0){ 17 set.add(nums[i]); 18 min=min<nums[i]?min:nums[i]; 19 max=max>nums[i]?max:nums[i]; 20 } 21 } 22 if(max-min>=5){ 23 return false; 24 } 25 return true; 26 } 27 }
分类:
leetcode
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术