Sword refers to the "Poker Straight" of the Offer series

LL is in a very good mood today, because he bought a deck of playing cards and found that there are actually 2 kings and 2 little kings in it (the deck of cards was originally 54)... He randomly drew 5 cards from it and wanted to test it. Feeling lucky, see if he can draw a straight, if he can draw, he decides to buy a sports lottery, hehe! ! "Heart Ace, 3 of Spades, Little King, Big King, Square Piece 5", "Oh My God!" It's not a straight... LL is not happy, he thought about it, and decided that Big\Little King can be regarded as any number, and A is regarded as 1, J is 11, Q is 12, and K is 13. The 5 cards above can be turned into "1,2,3,4,5" (big and small kings are regarded as 2 and 4 respectively), "So Lucky!". LL decided to buy a sports lottery. Now, you are asked to use this card to simulate the above process, and then tell us how lucky LL is. If the card can form a straight, it will output true, otherwise it will output false. For convenience, you can consider the size king to be 0.

Consider two situations:

  1. numbersThe case that does not contain 0:
    So how to judge? Because the need is a straight, first of all 不能有重复值, if there is no repeated value, then the shape is like [1 2 3 4 5]
    [5 6 7 8 9], you will find 最大值与最小值的差值应该小于5.

  2. numbersThe case where 0 is contained in: It is
    found that the value after 0 is removed, the judgment method is the same as that in 1.

Idea: First sort, and then record the position of the last 0, because 0 represents the size of the king, it can act as any number, and then traverse from the smallest number except 0. If there are the same numbers, then it must be false. If traversed After that, I found that there is no same number except 0, and finally judge whether the difference between the maximum value and the minimum value other than 0 is less than 5

import java.util.Arrays;

public class Solution {
    
    
    public boolean isContinuous(int[] numbers) {
    
    
        int len = numbers.length;
        if(len == 0 || numbers == null) return false;
        Arrays.sort(numbers);
        int i = 0; 
        for(int j = 0; j < len; j++){
    
    
            if(numbers[j] == 0) {
    
    
                i++; // i记录最小值的下标
                continue;
            }
            if(j+1 < len && numbers[j] == numbers[j+1]){
    
    
                return false;
            }
        }
        return numbers[len-1] - numbers[i] < 5;
    }
}

Time complexity: O(NlogN)
Space complexity: O(1)

Guess you like

Origin blog.csdn.net/weixin_44471490/article/details/108943705