当前位置:网站首页>[Jianzhi offer] 61 Shunzi in playing cards

[Jianzhi offer] 61 Shunzi in playing cards

2022-07-05 16:58:00 LuZhouShiLi

The finger of the sword Offer 61. Shunzi in playing cards

subject

  Draw at random from several sets of playing cards 5 card , Judge whether it's a down son , Is this 5 Are cards continuous .2~10 For the number itself ,A by 1,J by 11,Q by 12,K by 13, And big 、 Wang Wei 0 , It can be seen as any number .A Can't be regarded as 14.

Ideas

Three things

  • First, sort the array
  • In the statistics array 0 The number of
  • Finally, count the total number of vacancies between adjacent numbers in the sorted array
  • Judge 0 Whether the number of is greater than or equal to the total number of vacancies

Code

class Solution {
    
public:
    bool isStraight(vector<int>& nums) {
    
        sort(nums.begin(),nums.end());//  Sort 

        int king = 0;
        int gap = 0;

        for(int i = 0; i < nums.size(); ++i)
        {
    
            if(nums[i] == 0)
            {
    
                ++king;//  Statistics 0 The number of 
            }

            if(i > 0 && nums[i] != 0 && nums[i] == nums[i - 1])
            {
    
                return false;//  Encounter the same number 
            }

            if(i > 0 && nums[i - 1] != 0 && nums[i] > nums[i - 1] + 1)
            {
    
                gap += nums[i] - nums[i - 1] - 1;//  Calculate vacancy   Remember to subtract one 
            }
        }


        return king >= gap;// Judge 0 Whether the number of is greater than the number of vacancies 
    }
};

原网站

版权声明
本文为[LuZhouShiLi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051621564120.html