LeetCode334【动态规划】:递增的三元子序列

给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。

数学表达式如下:

如果存在这样的 i, j, k,  且满足 0 ≤ i < j < k ≤ n-1,
使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。

示例 1:

输入: [1,2,3,4,5]
输出: true
示例 2:

输入: [5,4,3,2,1]
输出: false

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-triplet-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

// 参考方法:
class Solution {
    public boolean increasingTriplet(int[] nums) {
        if (nums==null||nums.length<3) return false;
        int big=Integer.MAX_VALUE,small=Integer.MAX_VALUE;
        for (int i:nums){
            // 通过if的结构保证递增!
            if (i<=small) small=i;
            // 走到这一步说明这个值大于前面的值(i>small)
            else if (i<=big) big=i;
            // 走到这一步说明这个值大于前面的两个值(i>big>small)
            else return true;
        }
        return false;
    }
}

// 动态规划方法:遍历所有条件
class Solution {

    public boolean increasingTriplet(int[] nums) {
        int[] ints = new int[4];
        for (int i = 0;i < 4; i++) {
            ints[i] = 0x80000000;
        }
        return robot(nums, 0, 0, ints);
    }

    public boolean robot(int[] nums, int idx, int key, int[] ints) {
        if (ints[3] > 0x80000000) {
            return true;
        }
        if (idx >= nums.length) {
            return false;
        }
        boolean ans1 = false, ans2 = false, ans3 = false, ans4 = false, ans5 = false, ans6 = false, ans7= false;
        if (nums[idx] > ints[key]) {
            key++;
            ints[key] = nums[idx];
            ans1 = robot(nums, idx + 1, key, ints);
        } else if (nums[idx] < ints[key]){
            if (key == 2) {
                if (nums[idx] < nums[1]) {

                    ans7 = robot(nums, idx + 1, 2, ints);
                    ints[1] = nums[idx];
                    ints[2] = 0x80000000;
                    ans2 =  robot(nums, idx + 1, 1, ints);
                } else if (nums[idx] > nums[1]) {
                    ints[2] = nums[idx];
                    ans3 =  robot(nums, idx + 1, 2, ints);
                } else {
                    ans5 = robot(nums, idx + 1, 2, ints);
                }
            }
            if (key == 1){
                ints[1] = nums[idx];
                ans4 =  robot(nums, idx + 1, 1, ints);
            }
        } else {
            ans6 =  robot(nums, idx + 1, key, ints);
        }
        return ans1 || ans2 || ans3 || ans4 || ans5 || ans6 || ans7;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值