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 };