1. 程式人生 > >【LeetCode & 劍指offer刷題】數組題17:Increasing Triplet Subsequence

【LeetCode & 劍指offer刷題】數組題17:Increasing Triplet Subsequence

nac special include test mona wrap fff 17. 3.3

【LeetCode & 劍指offer 刷題筆記】目錄(持續更新中...)

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 < kn-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. Credits: Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
C++
/* 判斷是否存在增序排列的三元子序列(元素不用連續) 用兩個臨時變量存儲第一個數和第二個數,x當做第三個數 例1: input = [1 4 2 5 3] c1,c2初始化為最大值INT_MAX c1 = 1 c2 = 4 -> c2 =2 -> c3 =5 ,return true 例2: [2 4 1 5] c1 = 2,c2 = 4,c1 = 1,c3 = 5,return true, 能走到c3說明存在,但是c1,c2, c3存的數並不一定是符合要求的(順序可能不對) O(n),O(1) 類似問題:Longest Increasing Subsequence
*/ #include <climits> class Solution { public: bool increasingTriplet(vector<int>& a) { if(a.size()<3) return false; int c1 = INT_MAX,c2 = INT_MAX; for(int x:a) { if(x<=c1) c1 = x; //c1為掃描過程中遇到的最小數,是第一個數的候選 else if(x<=c2) c2 = x; //當x>c1時,x可能為c2或者c3 else return true; //c1<c2<x,說明這樣的三元子序列存在 } return false; } }; /*錯誤:沒有考慮元素可以不連續 class Solution { public: bool increasingTriplet(vector<int>& a) { if(a.size()<3) return false; for(int i = 0; i<a.size()-2; i++) //從第一個數掃描至倒數第3個元素 { if(a[i]<a[i+1] && a[i+1] < a[i+2]) return true; } return false; } };*/

【LeetCode & 劍指offer刷題】數組題17:Increasing Triplet Subsequence