1. Knowledge points of this question
Array
2. Title description
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 drew 5 cards at random and wanted to test it. Test his luck to see if he can draw a straight. If he can draw, he decides to buy a sports lottery, hehe! ! "Heart Ace, Spades 3, Little King, Big King, Square Piece 5", "Oh My God!" 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 the 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.
3. Problem solving ideas
To make a straight with 5 cards, the following two conditions must be met:
- The difference between the maximum value and the minimum value other than 0 must be less than 5
- Cannot have repeated values other than 0
The idea of solving the problem is as follows:
- Sort the array first to facilitate finding duplicate values
- Iterate over the array
- Find the minimum subscript other than 0
- Two adjacent non-zero elements are equal, return false
- If the difference between the maximum value and the minimum value other than 0 is less than 5, a straight is formed
4. Code
public class Solution {
public boolean IsContinuous(int [] numbers) {
if (numbers.length == 0) {
return false;
}
// 对数组进行排序
Arrays.sort(numbers);
// 最小值下标
int minIndex = 0;
// 遍历数组
for (int i = 0; i < numbers.length; i++) {
// 找出除 0 以外的最小值下标
if (numbers[i] == 0) {
minIndex++;
}
// 不能有除 0 以外的重复值
if (i > 0 && numbers[i] != 0 && numbers[i] == numbers[i - 1]) {
return false;
}
}
// 最大值和除 0 以外的最小值的差值要小于 5
if (numbers[numbers.length - 1] - numbers[minIndex] < 5) {
return true;
}
return false;
}
}