Sword refers to Offer-42-poker straight

Title description

LL was in a very good mood today, because he bought a deck of playing cards and found that there were 2 big 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. Test his luck and 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.

Idea analysis

When I first looked at the question, I was dumbfounded. 54 cards, it passes in the array, and then I simulate the process of drawing cards, get a random function, and then get 5 cards? Then determine if it is a straight? Then return?
It seems that other people’s explanations are known. The original number array is just 5 cards drawn. You only need to judge.

First of all, we can consider using a card because the 0 represented by the big and small king is a universal card, therefore, we can not consider it when sorting.
Then, we need to get the situation of a few cards other than 0.
In fact, to meet the condition of a straight, for these 5 cards, the face value of the largest card minus the face value of the smallest card must be less than 5. So this is a judgment that returns the result.
At the same time, we also need to pay attention that if there are duplicate cards other than 0 in the 5 cards, then it must not form a 5 card straight. So it needs to be considered.

Code

import java.util.TreeSet;
public class Solution {
    
    
    public boolean isContinuous(int [] numbers) {
    
    
       if(numbers == null || numbers.length == 0) return false;
        TreeSet<Integer> set = new TreeSet<Integer>();
        int count = 0;//用于记录放入set的0的牌数
        for(int i = 0;i<numbers.length;i++){
    
    
            if(numbers[i]==0){
    
    
                count++;
            }else{
    
    
               set.add(numbers[i]);   
            }
        }
        if((count+set.size())!=5){
    
    
            //如果放入的牌数和集合的和不等5说明出现了重复的牌,必然没有5个连续的拍
            return false;
        }
        //集合中最大的数减去最小的数,差小于等于5,说明是连续的或者可以用万能牌大小王拼成连续的
        if((set.last() - set.first())<5){
    
    
            return true;
        }
        //
        return false;
    }
}

Insert picture description here

Guess you like

Origin blog.csdn.net/H1517043456/article/details/107453669