zoukankan      html  css  js  c++  java
  • LeetCode 剑指 Offer 61. 扑克牌中的顺子 模拟

    地址 https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/

    从扑克牌中随机抽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] .
    

      

    算法1
    先排序
    遍历牌组 尝试组成顺子的时候 如果没有那张牌则补上癞子0
    注意有两张相同的非癞子牌 肯定不能组成五张顺子(抽屉原理)

    class Solution {
    public:
        bool isStraight(vector<int>& nums) {
            if(nums.size()>10) return true;
            sort(nums.begin(),nums.end());
            int l = 0; int need = -1;
            for(int i =0; i< nums.size();i++){
                if(nums[i] ==0) l++;
                else if(need==-1 ){
                    need = nums[i]+1;
                }else{
    
                    if(need > nums[i]) return false;
                    else if(need<nums[i]){
                        if(nums[i]-need > l) return false;
                        else {
                            l -= nums[i]-need;
                        }
                    }
                     need = nums[i]+1;
                }
            }
    
            return true;
        }
    };
  • 相关阅读:
    01_计算机基础
    09_哈希表
    08_查找算法
    Swagger使用
    Thymeleaf代码实例
    Spring boot代码实例
    Spring mvc代码实例
    Hibernate代码实例
    Mysql JDBC代码实例
    Mybatis代码实例
  • 原文地址:https://www.cnblogs.com/itdef/p/14274069.html
Copyright © 2011-2022 走看看