Returns an unordered integer sequence and determines whether an ascending triple subsequence exists. If I, j, and k exist, arr [I] returns true; if not, false.
Solution 1
Public static void main (String [] args ){
Int [] inputNums = {6, 4, 3, 2, 4, 7, 1 };
System. out. println (isExist (inputNums ));
}
Public static boolean isExist (int [] inputNums ){
If (inputNums. length <2 ){
Return false;
}
Int smallestBefore = inputNums [0];
Boolean [] existSmallerArray = new boolean [inputNums. length];
For (int I = 1; I <inputNums. length; I ++ ){
If (inputNums [I]> smallestBefore ){
ExistSmallerArray [I] = true;
} Else {
SmallestBefore = inputNums [I];
}
}
Int largestAfter = inputNums [inputNums. length-1];
For (int I = inputNums. length-2; I> = 0; I --){
If (inputNums [I] <largestAfter & existSmallerArray [I]) {
Return true;
}
If (inputNums [I]> = largestAfter ){
LargestAfter = inputNums [I];
}
}
Return false;
}
Ideas
I used the brute-force cracking method at first, and the time consumed was O (N3 ). If you need to find an incremental binary group, you can use the O (N) traversal method, but in solving the problem, the premise of comparing the second and third numbers is that the second number is greater than the first number, and this premise is based on the traversal of the array, so O (N3) is formed ).
The optimization we can think of is that the first loop is used to traverse and compare one side. When the comparison is true, it enters the next loop. At this time, the space complexity is O (N2)
If you do not want to nest the next loop, you can use an array to store the status of the comparison. Open another loop and compare the traversal results using the data in the array. The spatial complexity of this method is O (N ).
Solution 2
Public static boolean isExist2 (int [] inputNums ){
If (inputNums. length <3 ){
Return false;
}
Int first = Integer. MAX_VALUE;
Int second = Integer. MAX_VALUE;
For (int I = 0; I <inputNums. length; I ++ ){
If (inputNums [I] <first ){
First = inputNums [I];
Continue;
}
If (inputNums [I]> first & inputNums [I] <second ){
Second = inputNums [I];
Continue;
}
If (inputNums [I]> second ){
Return true;
}
}
Return false;
}
Ideas
The previous two comparison states are retained among the first and second variables, and the maximum number of the third variable is only compared with the second storage variable.