[LeetCode][JavaScript]Increasing Triplet Subsequence

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.

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


寻找序列中是否存在三个递增的数,要求O(n)的时间复杂度和O(1)的空间复杂度。
基本思路是开双指针,p指向最小的数,q指向这个最小数之后次小的数,如果还有第三个数大于q,返回true。

需要仔细思考虑的一个情况是[0,2,-1,3]。
当遍历到-1的时候,p是0,q是2,此时如果把-1当做最小的数,-1和3不能够成三个递增的数。
这里的做法是直接把p替换成-1,此时p是-1,q是2,再遇到3的时候,发现3大于q,直接返回true。
也就是说q其实有两个作用,一般是记录当前递增序列第二小的数,当出现例子中的情况时,q的作用就是记录之前遇到的第二小的数,如果后面的结果再次小于q,直接覆盖q的值。

也可以把q拆成两个变量,代码啰嗦一点而已。

 1 /**
 2  * @param {number[]} nums
 3  * @return {boolean}
 4  */
 5 var increasingTriplet = function(nums) {
 6     var p = Infinity, q = Infinity;
 7     for(var i = 0 ; i < nums.length; i++){
 8         if(nums[i] <= p){
 9             p = nums[i];
10         }else if(nums[i] < q){
11             q = nums[i];
12         }else if(nums[i] > q){
13             return true;
14         }
15     }
16     return false;
17 };