168.Increasing Triplet Subsequence

来源:互联网 发布:手机歌曲后期制作软件 编辑:程序博客网 时间:2024/05/27 06:51

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.

Subscribe to see which companies asked this question.

典型的动态规划问题.

定义数组dp,dp[i]表示nums[0...i]之间的最大递增子序列的长度。

所以,根据dp[0..i-1],求i时:从所有满足nums[i]>nums[j](j=0..i-1)的j中选择最大的dp[j],然后加1即为求得的dp[i]。

最后选择dp数组中的最大值即得到数组中最大递增子序列的长度。然后根据这个长度是否大于 3 返回 true 或 false.

public boolean increasingTriplet(int[] nums) {        return lengthOfLIS(nums) >= 3 ? true : false;    }            /** * 典型的动态规划问题. * 定义数组dp,dp[i]表示nums[0...i]之间的最大递增子序列的长度。 * 所以,根据dp[0..i-1],求i时:从所有满足nums[i]>nums[j](j=0..i-1)的j中选择最大的dp[j],然后加1即为求得的dp[i]。 * 最后选择dp数组中的最大值 */public int lengthOfLIS(int[] nums) {int len = nums.length;if(len <= 1){return len;}/*定义数组dp,dp[i]表示nums[0...i]之间的最大递增子序列的长度。*/int dp[] = new int[len];dp[0] = 1;/*计算dp数组*/for(int i = 1;i<len;i++){int maxdp = 0;for(int j = 0; j<i; j++){if(nums[i] > nums[j] && maxdp < dp[j]){maxdp = dp[j];}}dp[i] = maxdp + 1;}/*选择dp数组中最大的*/int max = dp[0];for(int i = 0;i<len;i++){if(max < dp[i]){max = dp[i];}}return max;}



0 0
原创粉丝点击