Increasing Triplet Subsequence

update Aug 14,2017 21:21

LeetCodearrow-up-right

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.

Basic Idea:

要解决这个问题,我们只需要在遍历时想办法跟踪当前位置之前最小的和第二小的数,准确讲,其实只是需要跟踪当前位置之前第二小的数,那么只要发现比当前第二小大的数,就说明三元递增序列了。

Java Code:

update Nov 30, 2017

更新

时隔数月重新考虑这道题目的时候,思路是对的,但却没有看出只需要跟踪当前第二小这一点。在实现的时候,<= 的判断条件很重要;

更新一个Python的solution: