Given an unsorted array return whether an 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.
一刷
题解:类似于动态规划。保存the first smallest, the second smallest,
并不断update这两个值。如果比这两个都大,return true
注意,small和big的位置不重要,如果大于big, 则一定大于big之前的small, 因为会先对small赋值才会对big赋值。big之前,一定有比big小的small.
class Solution {
public boolean increasingTriplet(int[] nums) {
int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE;
for(int num : nums){
if(num<=small) small = num;//update the first smallest
else if(num<=big) big = num;//update the second smallest
else return true;
}
return false;
}
}