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
- 168.Increasing Triplet Subsequence
- 334. Increasing Triplet Subsequence
- leetcode Increasing Triplet Subsequence
- LeetCode - Increasing Triplet Subsequence
- [LeetCode] Increasing Triplet Subsequence
- Increasing Triplet Subsequence
- LeetCode Increasing Triplet Subsequence
- Leetcode:Increasing Triplet Subsequence
- 334. Increasing Triplet Subsequence
- Increasing Triplet Subsequence
- LeetCode:Increasing Triplet Subsequence
- 334. Increasing Triplet Subsequence
- leetcode:Increasing Triplet Subsequence
- [LeetCode]Increasing Triplet Subsequence
- (java)Increasing Triplet Subsequence
- 334. Increasing Triplet Subsequence
- 334. Increasing Triplet Subsequence
- LeetCode334. Increasing Triplet Subsequence
- 167.Longest Increasing Subsequence
- 常用化简
- Spark streaming 应用简单示例
- 模拟post表单提交
- HTTP/2 新特性浅析
- 168.Increasing Triplet Subsequence
- deque
- 欢迎使用CSDN-markdown编辑器
- c语言中顺序表的实现
- 16位汇编 cmp jne实现判断和循环
- string 类的几个函数 源码实现
- VS2010下Heap corruption排查一例
- Ubuntu安装更新最新版本R
- 面试题之对称的二叉树,层序遍历(每层节点打印成一行),平衡二叉树的判断