题目
题解
双向遍历
维护数组 nums 中的每个元素左边的最小值和右边的最大值,只要出现leftMin[i] < nums[i] < rightMax[i],即返回true
class Solution {
public boolean increasingTriplet(int[] nums) {
int n=nums.length;
if(n<3)
return false;
int[] leftMin=new int[n];
leftMin[0]=nums[0];
for(int i=1;i<n;i++){
leftMin[i]=Math.min(leftMin[i-1],nums[i]);
}
int[] rightMax=new int[n];
rightMax[n-1]=nums[n-1];
for(int i=n-2;i>=0;i--){
rightMax[i]=Math.max(rightMax[i+1],nums[i]);
}
//遍历中间值nums[i]
for(int i=1;i<n-1;i++){
if(nums[i]>leftMin[i]&&nums[i]<rightMax[i])
return true;
}
return false;
}
}
时间复杂度: O ( n ) O(n) O(n),遍历数组三次
空间复杂度: O ( n ) O(n) O(n),三个数组
贪心
使用贪心策略将空间复杂度降到O(1),其核心思想为:为了找到递增的三元子序列,三元组第一个元素 first 和 第二个元素 second 应该尽可能地小,此时找到递增的三元子序列的可能性更大。
具体算法如下:赋初始值,first=nums[0],second=+∞,已经满足second > first了,现在找第三个数third
(1) 如果third比second大,那就是找到了,直接返回true
(2) 如果third比second小,但是比first大,那就把second的值设为third,然后继续遍历找third
(3) 如果third比first还小,那就把first的值设为third,然后继续遍历找third
class Solution {
public boolean increasingTriplet(int[] nums) {
int n=nums.length;
if(n<3)
return false;
int first=nums[0],second=Integer.MAX_VALUE;
for(int i=1;i<n;i++){
int third=nums[i];
if(third>second)//1<2<3
return true;
else if(third>first)//1<3<2
second=third;
else//3<1<2
first=third;
}
return false;
}
}
时间复杂度: O ( n ) O(n) O(n),遍历数组一次
空间复杂度: O ( 1 ) O(1) O(1)