1. 程式人生 > >[LeetCode]334 三個遞增數字子序列

[LeetCode]334 三個遞增數字子序列

Increasing Triplet Subsequence(三個遞增數字子序列)

【難度:Medium】
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.
給定一亂序陣列,判斷其內部是否存在三個順序遞增的數字子序列,
如存在0<= i < j < k <= n-1,使得a[i]

解題思路

設定兩個變數fisrt,second來記錄已出現的兩個遞增的數字,遍歷陣列,且維護first<second的關係,那麼當出現一個數字大於second時,則存在符合條件的遞增子序列,返回true,否則返回false。

c++程式碼如下:

class
Solution { public: bool increasingTriplet(vector<int>& nums) { if (nums.size() < 3) return false; int first = INT_MAX; int second = INT_MAX; for (int i = 0; i < nums.size(); i++) { if (nums[i] <= first) { first = nums[i]; } else
if (nums[i] <= second) { second = nums[i]; } else { return true; } } return false; } };