leetcode-334. Increasing Triplet Subsequence
阿新 • • 發佈:2018-01-01
color bool vector pro 限制 下一步 spa style span
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