Topic describes

Draw 5 cards randomly from the playing card to determine whether it is a straight, that is, the 5 cards are not consecutive. A is 1. J is 11. Q is 12. A cannot be considered 14.

Source: LeetCode

Example 1:

Input: [1,2,3,4,5] output: TrueCopy the code

Example 2:

Input: [0,0,1,2,5] output: TrueCopy the code

Limitations:

The array length is 5

The number of arrays is [0, 13].

Thought analysis

We are asked to determine whether the elements in the given array nums are contiguous, and that element 0 is a wild card that can be converted to any value in the range [0,13].

So first of all, we can sort this array and see if there’s a 0 in the array based on the header element.

  1. If the number of zeros is greater than or equal to 4, return true. Returns true as long as the gap between the remaining elements in the array is no greater than the number of elements 0, and there can be no duplicate elements (except 0). Otherwise return false.

  2. No 0, to judge the whole array element continuity (i.e. the nums [4] – nums [3] = = 1 && nums [3] – nums [2] = = 1 && nums [2] – nums [1] = = 1 && nums [1] – nums [0] = = 1), satisfactory returns true, Otherwise return false.

AC code

var isStraight = function(nums) {
    nums.sort((a,b) = >a-b);
    if(nums[0] = =0)
    {
        // start records elements whose values are not 0
        start= nums.findIndex(a= >a! =0);
        if(start>=3)
            return true;
        // arr converts the Set type to see if there are duplicates other than 0
        const arr  = new Set(nums.slice(start));
        if(nums.length-start! =arr.size)return false;
        // count Specifies the space between elements in the array except 0
        let count = 0;
        for(let i= nums.length-1; i>start; i--) { count = count + nums[i]-nums[i-1] -1;
        }
        if(count>start+1)
            return false
        else
            return true; 
    }
    else
    {
        if(nums[4]-nums[3] = =1&&nums[3]-nums[2] = =1&&nums[2]-nums[1] = =1&&nums[1]-nums[0] = =1)
            return true;
        else
            return false; }};Copy the code

The last

This is No.7 of my LeetCode flash card, and the following chapters are waiting to be updated. If you like this LeetCode post, please like 😄

This article is participating in the “Gold Digging march Campaign”, click to see the details of the campaign.