Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
Topic describes
From a number of cards in a deck of cards randomly selected 5 cards, judge whether a straight, that is, the 5 cards are not continuous. A is 1. J is 11. Q is 12. A cannot be considered 14.
- 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 is5The number of arrays is [0.13]
Copy the code
Train of thought
According to the problem array, it needs to satisfy:
The difference between the maximum and minimum of an array cannot be more than 4, except 0. An array of five consecutive digits must satisfy this condition. The array of five consecutive digits must not have the same number except 0.
To directly obtain the maximum number and minimum number of the array, we must sort the array to get the maximum number and minimum number of the array, and determine whether the difference between them is greater than 4. If the difference is greater than 4, it does not match the description. Return false if all of the above statements are true
/ * * *@param {number[]} nums
* @return {boolean}* /
function isStraight(nums) {
nums = nums.sort((a,b) = > a - b)
let len = nums.length
let min = 0
let minIndex = 0
let max = nums[len - 1]
for(let i = 0; i < len; i++) {
if(nums[i] ! =0) {
min = nums[i]
minIndex = i
break}}let set = new Set(nums.slice(minIndex))
return (set.size == len - minIndex) && (max - min < 5)};Copy the code