[leetcode] 334. Increasing Triplet Subsequence
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] 334. 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 < 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
.
Solution:
这里只需求出BIS3即可。
1、找到最小的数min1, 其位置为k1.
2、找到第二小的数min2, 其位置为k2 > k1.
3、如果k3(k3>k2)位置的数n>min2, 找到递增三元组(min1, min2, n)
如果n<=min1, 更新min1=n和k1 = k3, 如果n<=min2, 更新k2和min2.
1 bool increasingTriplet(vector<int>& nums) 2 { 3 int min1 = INT_MAX, min2 = INT_MAX; 4 5 for (int i = 0; i < nums.size(); i++) 6 { 7 if (nums[i] <= min1) 8 min1 = nums[i]; 9 else if (nums[i] <= min2) 10 min2 = nums[i]; 11 else 12 return true; 13 } 14 15 return false; 16 }
以上是关于[leetcode] 334. Increasing Triplet Subsequence的主要内容,如果未能解决你的问题,请参考以下文章
leetcode-334. Increasing Triplet Subsequence
LeetCode 334. Increasing Triplet Subsequence