Given an unsorted array return whether a increasing subsequence of length 3 exists or not in the array.
Formally the function should:
Return True if there exists
I, J, K
such that
Arr[i] <
arr[j] <
arr[k] given 0≤
i <
J <
k ≤
n-1 else return false.
Your algorithm should run in O (n) time complexity and O (1) space complexity.
Examples:
Given [1, 2, 3, 4, 5] ,
Return true .
Given [5, 4, 3, 2, 1] ,
Return false .
This problem and Leetcode 300. Longest increasing subsequence--the longest ascending subsequence is actually the same, but increases the limitation of time and space complexity. In fact, because just to determine if there is a ternary increment sequence, then when the list of elements reached three, you can return to ture, and every time you look for replacement elements only in two select a large, so so-called two search is actually only used in the constant number of times. So in fact, based on the No. 300 question slightly modified to get the code can be passed.
Optimization is actually the modification of the process to translate, set two variables num1,num2, initially set to the maximum value. Traversing the array, if there is smaller than the NUM1, the num1 into that element, if there is larger than the NUM1 and smaller than the num2, the num2 replaced, these two steps are actually in the simulation of the No. 300 element of the replacement. Finally, when there are larger numbers than NUM1 and num2, then you can return true directly, which is equivalent to simulating list.size () = = 3.
Java
classSolution { Public BooleanIncreasingtriplet (int[] nums) { intNUM1 = integer.max_value, num2 =Integer.max_value; for(inti = 0; i < nums.length; i++) { if(Nums[i] < NUM1) NUM1 =Nums[i]; Else if(Nums[i] > NUM1 && nums[i] < num2) num2 =Nums[i]; Else if(Nums[i] > num2)return true; } return false; }}
(Java) Leetcode 334. Increasing Triplet subsequence--increment of ternary subsequence