给你一个整数数组 nums
,判断这个数组中是否存在长度为 3
的递增子序列。
如果存在这样的三元组下标 (i, j, k)
且满足 i < j < k
,使得 nums[i] < nums[j] < nums[k]
,返回 true
;否则,返回 false
。
示例 1:
输入:nums = [1,2,3,4,5] 输出:true 解释:任何 i < j < k 的三元组都满足题意
示例 2:
输入:nums = [5,4,3,2,1] 输出:false 解释:不存在满足题意的三元组
示例 3:
输入:nums = [2,1,5,0,4,6] 输出:true 解释:三元组 (3, 4, 5) 满足题意,因为 nums[3] == 0 < nums[4] == 4 < nums[5] == 6
提示:
1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
进阶:你能实现时间复杂度为 O(n)
,空间复杂度为 O(1)
的解决方案吗?
用 min, mid 记录遍历过程中遇到的最小值以及中间值,若出现 num > mid,说明找到了满足题目的三元组,返回 true;否则遍历结束返回 false。
class Solution:
def increasingTriplet(self, nums: List[int]) -> bool:
mi, mid = inf, inf
for num in nums:
if num > mid:
return True
if num <= mi:
mi = num
else:
mid = num
return False
class Solution {
public boolean increasingTriplet(int[] nums) {
int n = nums.length;
int[] lmi = new int[n];
int[] rmx = new int[n];
lmi[0] = Integer.MAX_VALUE;
rmx[n - 1] = Integer.MIN_VALUE;
for (int i = 1; i < n; ++i) {
lmi[i] = Math.min(lmi[i - 1], nums[i - 1]);
}
for (int i = n - 2; i >= 0; --i) {
rmx[i] = Math.max(rmx[i + 1], nums[i + 1]);
}
for (int i = 0; i < n; ++i) {
if (lmi[i] < nums[i] && nums[i] < rmx[i]) {
return true;
}
}
return false;
}
}
空间优化:
class Solution {
public boolean increasingTriplet(int[] nums) {
int min = Integer.MAX_VALUE, mid = Integer.MAX_VALUE;
for (int num : nums) {
if (num > mid) {
return true;
}
if (num <= min) {
min = num;
} else {
mid = num;
}
}
return false;
}
}
function increasingTriplet(nums: number[]): boolean {
let n = nums.length;
if (n < 3) return false;
let min = nums[0],
mid = Number.MAX_SAFE_INTEGER;
for (let num of nums) {
if (num <= min) {
min = num;
} else if (num <= mid) {
mid = num;
} else if (num > mid) {
return true;
}
}
return false;
}
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int mi = INT_MAX, mid = INT_MAX;
for (int num : nums) {
if (num > mid) return true;
if (num <= mi)
mi = num;
else
mid = num;
}
return false;
}
};
func increasingTriplet(nums []int) bool {
min, mid := math.MaxInt32, math.MaxInt32
for _, num := range nums {
if num > mid {
return true
}
if num <= min {
min = num
} else {
mid = num
}
}
return false
}
impl Solution {
pub fn increasing_triplet(nums: Vec<i32>) -> bool {
let n = nums.len();
if n < 3 {
return false;
}
let mut min = i32::MAX;
let mut mid = i32::MAX;
for num in nums.into_iter() {
if num <= min {
min = num;
} else if num <= mid {
mid = num;
} else {
return true;
}
}
false
}
}