LeetCode-334. Increasing Triplet Subsequence

时间:2021-08-01 13:20:14

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.

题目大意是判断所给的数组中是否存在长度为3的递增序列。

最常规的办法应该是两层循环,逐个判断。时间复杂度较高。还有一种比较巧妙的办法,维护两个距离最近的递增序列,如果能找到第三个则返回true。设置一个small,一个big,small<big。如果能找到一个不小于small和big的就返回true。时间复杂度为O(n)

实现代码:

public class Solution {
public boolean increasingTriplet(int[] nums) {
if(nums == null || nums.length < 3)
return false;
int small = Integer.MAX_VALUE, big = Integer.MAX_VALUE;
for(int value : nums) {
if(value <= small)
small = value;
else if(value <= big)
big = value;
else
return true;
} return false;
}
}