334 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
.
思路
首先寻找一个前后递增的关系,即找到序列中,后一个数比前一个数大的情况。如果没有则返回False
。这是在第一个while循环里面进行的。
接下来我们寻找第三个数,如果找到的第三个数比前两个数都要大,返回True
。
我们把前面找到的两个数分别维护起来,分别为low
和mid
。如果找到的数如果比mid
小,却low
大,将mid
的值置换为该数;
如果找到的数比low
小,可以暂存起来,放进low_tmp
中,看此数之后还有没有比它大的数。