原题
给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回 true ;否则,返回 false 。示例 1:输入:nums = [1,2,3,4,5]
输出:true
解释:任何 i < j < k 的三元组都满足题意
示例 2:输入:nums = [5,4,3,2,1]
输出:false
解释:不存在满足题意的三元组
示例 3:输入:nums = [2,1,5,0,4,6]
输出:true
解释:三元组 (3, 4, 5) 满足题意,因为 nums[3] == 0 < nums[4] == 4 < nums[5] == 6提示:1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1进阶:你能实现时间复杂度为 O(n) ,空间复杂度为 O(1) 的解决方案吗?来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-triplet-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
动态规划,但是此处动态规划不是最优解,需要再思考一下。
代码
public class Solution_334 {
public static void main(String[] args) {
int[] nums = {
20, 100, 10, 12, 5, 13};System.out.println(increasingTriplet(nums));}public static boolean increasingTriplet(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();for (int i = 0; i < nums.length; i++) {
set.add(nums[i]);}if (set.size()<3){
return false;}int[] dp = new int[nums.length];Arrays.fill(dp, 1);int max = 0;for (int i = 1; i < dp.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);}}max = Math.max(dp[i], max);}if (max < 3) {
return false;} else {
return true;}}
}