問題:數組
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.spa
Formally the function should:code
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.orm
Examples:
Given [1, 2, 3, 4, 5]
,
return true
.ip
Given [5, 4, 3, 2, 1]
,
return false
.it
解決:io
① 要求O(n)的時間複雜度和O(1)的空間複雜度。function
遍歷數組,維護一個最小值,和倒數第二小值,遍歷原數組的時候,若是當前數字小於等於最小值,更新最小值,若是小於等於倒數第二小值,更新倒數第二小值,若是當前數字比最小值和倒數第二小值都大,說明此時有三個遞增的子序列了,直接返回ture,不然遍歷結束返回false。class
class Solution { //7ms
public boolean increasingTriplet(int[] nums) {
int min = Integer.MAX_VALUE;
int secmin = Integer.MAX_VALUE;
for (int n : nums){
if (min >= n){
min = n;
}else if (secmin >= n && min < n){
secmin = n;
}else{
return true;
}
}
return false;
}
}遍歷