leetcode-334. Increasing Triplet Subsequence

Posted jiu__

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-334. Increasing Triplet Subsequence相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/increasing-triplet-subsequence/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.

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

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

题意很明确,在一个序列里确认三元递增子序列的存在性。限制O(n)的时间复杂度和O(1)的空间复杂度。

方法:O(n)的时间复杂度,这往往通过设置标识变量来实现。唯一需要注意的是,别把问题想得太复杂了。。维护一个最小值和一个次小值,迭代更新即可。小技巧在于,自己需要想明白:更新最小值时,次小值在最小值前面,怎么维护?这个无需维护,可以理解为更新最小值后,该最小值后有一个虚拟的次小值与前面的次小值大小相同。推演下一步,自然就懂了。

程序:

 1 class Solution {
 2 public:
 3     bool increasingTriplet(vector<int>& nums) {
 4         int m1 = 0x7fffffff, m2 = 0x7fffffff;
 5         for (int a : nums) {
 6             if (m1 >= a) m1 = a;
 7             else if (m2 >= a) m2 = a;
 8             else return true;
 9         }
10         return false;
11     }
12 };

 

以上是关于leetcode-334. Increasing Triplet Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 334. Increasing Triplet Subsequence

LeetCode 334 Increasing Triplet

leetcode-334 Increasing Triplet Subsequence 解题记录

[leetcode] 334. Increasing Triplet Subsequence

leetcode 334. Increasing Triplet Subsequence

[LeetCode] 334. Increasing Triplet Subsequence 递增三元子序列