334. Increasing Triplet Subseque

2018-01-03  本文已影响12人  黑山老水

Description:

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.

Example:

Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],
return false.

Link:

https://leetcode.com/problems/increasing-triplet-subsequence/description/

解题方法:

见代码,这道题的思路是保证有两个数n1 < n2,如果再能找到一个大于n2的数就存在。
在这期间n1被更小的数更新了也无所谓,因为n2一直会大于n1。

Tips:

Time Complexity:

O(n) time complexity and O(1) space complexity

完整代码:

bool increasingTriplet(vector<int>& nums) {
    int n1 = INT_MAX, n2 = INT_MAX;
    for(int i: nums) {
        if(i <= n1)
            n1 = i;
        else if(i <= n2)
            n2 = i;
        else 
            return true;
    }
    return false;
}
上一篇下一篇

猜你喜欢

热点阅读