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.
題乾的意思是給定未排序數組,從中找到三個滿足arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1遞增數字時返回true,找不到返回false。
解題思路:
設定兩個數字min和middle,min保存已發現的最小值,middle保存僅比min大的第二小值。
if num <= min 則 min = num
else if num <= middle 則 middle = num
else 則return true;原因是 此時的num 肯定比min,middle都大,有min < middle < num
源碼如下:
/**
* Increasing Triplet Subsequence
* @param nums
* @return
*/
public boolean increasingTriplet(int[] nums) {
int min = Integer.MAX_VALUE;
int middle = Integer.MAX_VALUE;
for (int num : nums) {
if (num <= min) {
min = num;
} else if (num <= middle) {
middle = num;
} else {
return true;
}
}
return false;
}