Leetcode题解中级篇之数组和字符串(6)递增的三元子序列

题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/29/array-and-strings/80/

题目描述:

给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。

数学表达式如下:

如果存在这样的 
i, j, k,  且满足 0 ≤ 
i < 
j < 
k ≤ 
n-1,

使得 
arr[i] < 
arr[j] < 
arr[k] ,返回 true ; 否则返回 false 。

说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。

示例 1:

输入: [1,2,3,4,5]
输出: true

示例 2:

输入: [5,4,3,2,1]
输出: false

思路: 一开始想用动态规划 用dp[]记录每个位置已经满足i<j,nums[i]<nums[j] 条件的状态. 1 ,2 ,3  则dp[2]=3跳出. 可是要求空间复杂度为1 ,而且仔细想了下太多余了. 感觉用双指针+一个计数count 能解决.结果,不断调试都AC不了100% 

看了大神的思路.

思路有点类似动态规划的思想,维护一个二元组(first,second),记录第i个元素之前的“最小”递增二元子序列(对后续元素的要求最低如[5,6,2,3,4]会更新[5,6]为[2,3]此时只要后续满足大于3就可以)

当nums[i]小于first时,更新first的值
当nums[i]>first且nums[i]

原文:https://blog.csdn.net/whdAlive/article/details/80404875 

代码:

class Solution {
        public boolean increasingTriplet(int[] nums) {

            int first = Integer.MAX_VALUE,second = Integer.MAX_VALUE;
            if(nums.length<3){
                return false;
            }
            for(int num:nums){
                if(first>num){
                    first = num;
                }else if(first<num && second>num){
                    second = num;
                }else if(num>second){
                    return true;
                }
            }
            return false;
        }

    }


//空间复杂度为O(n)
public class Solution{
	public boolean increasing Triplet(int []nums){
		if(nums.lendth<2)
			return false;
		int n =nums.lendth;
		boolean[]has_first_small =new booleam[n];
		int smallest =num[0];
		has_first_small[0]=false;
		for(int i=0;i<n;i++){
			if(smallest <num[i]){
				has_first_small[i]=true;
			
			smallest =Math.min(smallest,num[i]);
		}
		int biggest =num[n-1];
		for(int i=n-2;i>=0;i--){
			if(has_first_small[i]==true){
				if(num[i]<biggest){
					return true;
				}
				biggest =Math.max(biggest,num[i]);
			}
		}
		return false;
	}
}

 

点赞