Increasing Triplet Subsequence

来源:互联网 发布:stm32串口接收数据 编辑:程序博客网 时间:2024/05/01 18:00

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.

Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.

思路:用两个变量来存储扫描过的第一大和第二大的值,然后如果有数比这两个值大,就return true;

public class Solution {    public boolean increasingTriplet(int[] nums) {        if(nums == null || nums.length < 3){            return false;        }               int m1 = Integer.MAX_VALUE;        int m2 = Integer.MAX_VALUE;       for(int i=0; i<nums.length; i++){           if(nums[i]<=m1) {               m1 = nums[i];           } else if(nums[i]<=m2){               m2 = nums[i];           } else {               return true;           }       }       return false;    }}

思路2:利用空间O(n),N^2的解法。就是建立一个数组,dp[i] 表达的意义就是到目前为止,小于等于当前值的个数(包括自己)。所以状态的更新依赖于前面的状态,所以这个是dp题,如果等于3,则返回true;

public class Solution {    public boolean increasingTriplet(int[] nums) {        if(nums == null || nums.length < 3){            return false;        }                int[] dp = new int[nums.length];        Arrays.fill(dp,1);        for(int i=1; i<nums.length; i++){            for(int j=0; j<i; j++){                if(nums[j] < nums[i]){                    dp[i] = Math.max(dp[i],dp[j]+1);                    if(dp[i]>=3) return true;                }            }        }        return false;    }}



0 0