为了账号安全,请及时绑定邮箱和手机立即绑定

增加三重态子序列

增加三重态子序列

aluckdog 2021-04-26 10:37:12
我正在解决以下问题:Given an unsorted array return whether an increasing subsequence of length 3 exists in the array or not. Formally return true if there exists i, j, k such that:arr[i]<arr[j]<arr[k] given 0 <= i < j < k <= n-1这是我的代码:public boolean increasingTriplet(int[] nums) {    if (nums.length < 3) return false;    for (int i = 0; i < nums.length-2; i++) {        if (nums[i] < nums[i+1]) {            if (nums[i+1] < nums[i+2]) return true;        }    }    return false;}我的代码在以下输入中失败:[5,1,5,5,2,5,4] 显然,对于此序列,我的代码应该返回true,但是由于我看不到长度3的任何增加的子序列,所以我无法弄清楚为什么这样做,对于理解此问题的任何帮助,我们将不胜感激。
查看完整描述

2 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

public boolean increasingTriplet(int[] nums) {

    int first=Integer.MAX_VALUE;

    int second=Integer.MAX_VALUE;

    int third=Integer.MAX_VALUE;


    for(int p=0; i<nums.length; p++){

        if(nums[p]<=third){

            third=nums[p];

        }else{

            if(nums[p]<=second){

                first=third;

                second=nums[p];

            }else{

                return true;

            }

        }

    }

    return false;

}

该代码背后的全部思想是,如果我们发现一对值按升序排列,则只有在新对的第一个值小于旧对的第一个值时,才可以用新的对数递增序列替换该对。新对的第二个值小于旧对的第二个值。同时,我们检查数字是否大于将完成序列的第二个数字(true在这种情况下,我们将返回)。


代码开始比较值从第三到第二,而不是第一到第二,但是思想与上面相同。


查看完整回答
反对 回复 2021-05-12
?
侃侃尔雅

TA贡献1801条经验 获得超16个赞

这是一种可能的解决方案:


public static boolean increasingTriplet(int[] nums) {

    for (int i = 0; i < nums.length-2; ++i) {

        for (int j = i+1; j < nums.length-1; ++j) {

            if (nums[j] > nums[i]) {

                for (int k = j+1; k < nums.length; ++k) {

                    if (nums[k] > nums[j]) {

                        return true;

                    }

                }

            }

        }

    }

    return false;

}


查看完整回答
反对 回复 2021-05-12
  • 2 回答
  • 0 关注
  • 191 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信