【Leetcode】Increasing Triplet Subsequence

题目链接:https://leetcode.com/problems/increasing-triplet-subsequence/

题目:

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.

思路:

1、c[i] = max{c[j]+1,1} j<i 且nums[i]>nums[j]

时间复杂度O(n^2),空间复杂度O(n)

2、

利用二分搜索,这里二分搜索的空间是常数项,所耗费的时间、空间都可以看成O(1)复杂度

算法1:

public boolean increasingTriplet(int[] nums) {  
    if (nums.length < 3)  
        return false;  
    int c[] = new int[nums.length];// c[i]表示从0~i 以nums[i]结尾的最长增长子串的长度  
    c[0] = 1;  
  
    for (int i = 1; i < nums.length; i++) {  
        int tmp = 1;  
        for (int j = 0; j < i; j++) {  
            if (nums[i] > nums[j]) {  
                tmp = Math.max(c[j] + 1, tmp);  
            }  
        }  
        c[i] = tmp;  
        if (c[i] >= 3)  
            return true;  
    }  
    return false;  
}  



算法2:


public boolean increasingTriplet(int[] nums) {  
    if (nums.length < 3)  
        return false;  
    int b[] = new int[3+1];// 长度为i的子串 最后一个数最小值  
    int end = 1;  
    b[end] = nums[0];  
  
    for (int i = 1; i < nums.length; i++) {  
        if (nums[i] > b[end]) {// 比最长子串最后元素还大,则更新最长子串长度  
            end++;  
            b[end] = nums[i];  
            if(end>=3)  
                return true;  
        } else {// 否则更新b数组  
            int idx = binarySearch(b, nums[i], end);  
            b[idx] = nums[i];  
        }  
    }  
    return false;  
}  
/** 
 * 二分查找大于t的最小值,并返回其位置 
 */  
public int binarySearch(int[] b, int target, int end) {  
    int low = 1, high = end;  
    while (low <= high) {  
        int mid = (low + high) / 2;  
        if (target > b[mid])  
            low = mid + 1;  
        else  
            high = mid - 1;  
    }  
    return low;  
}  


算法2:


你可能感兴趣的:(【Leetcode】Increasing Triplet Subsequence)