Sword Finger Offer—61. Poker Straight—Analysis and Code (Java)

Sword refers to offer-61. Poker straight-analysis and code [Java]

1. Title

LL was in a particularly good mood today, because he went to buy a deck of playing cards and found that there were actually 2 kings and 2 kings in it (the deck was originally 54 cards). He randomly drew 5 cards from it, wanted to test his own luck, to see if he could draw a straight, if he could, he decided 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.

Two, analysis and code

1. Judgment interval

(1) Thinking

First of all, if there are non-zero repeating numbers in the card, it cannot make a straight.
In the absence of repeated numbers, only the maximum and minimum values ​​other than 0 need to be counted. If the difference between the two is equal to 4 (at this time there are enough 0s to fill in), it can form a straight.

(2) Code

public class Solution {
    
    
    public boolean isContinuous(int [] numbers) {
    
    
        if (numbers.length != 5)
            return false;
        int flag[] = new int[13];
        for (int i = 0;i < 13; i++)
            flag[i] = 0;
        
        int minNum = 14, maxNum = 0;
        for (int i = 0; i < 5; i++) {
    
    
            if (numbers[i] == 0)
                continue;
            if (flag[numbers[i] - 1] != 0)
                return false;
            flag[numbers[i] - 1] = 1;
            minNum = Math.min(minNum, numbers[i]);
            maxNum = Math.max(maxNum, numbers[i]);
        }
        
        return ((maxNum - minNum) < 5);
    }
}

(3) Results

Running time: 15ms, occupied memory: 9256k.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/112127819