LeetCode刷题小记——#334. 递增的三元子序列

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

如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回 true ;否则,返回 false 。

https://leetcode-cn.com/problems/increasing-triplet-subsequence/https://leetcode-cn.com/problems/increasing-triplet-subsequence/

方法一:双向遍历法

这个方法有点暴力,用到了点dp的思想,开了两个长度为n的int型数组。

  • minLeft[i]表示从索引0到索引i,数组中的最小值 
  • maxRight[i]表示从索引i到索引n-1,数组中的最大值

最后来一个for循环,比较数组索引i处左边是否有小于nums[i]的值,索引i处右边是否有大于nums[i]的值,如果有返回true,如果循环结束还没有的话,最后返回false。

优点:思路清晰

缺点:时间复杂度和空间复杂度还可以再优化

class Solution {
    //双向遍历
    public boolean increasingTriplet(int[] nums) {
        int n = nums.length;
        
        int[] minLeft = new int[n];
        minLeft[0] = nums[0];
        for(int i = 1; i < n; i++) {
            minLeft[i] = Math.min(minLeft[i - 1], nums[i]);
        }

        int[] maxRight = new int[n];
        maxRight[n - 1] = nums[n - 1];
        for(int i = n - 2; i >= 0; i--) {
            maxRight[i] = Math.max(maxRight[i + 1], nums[i]);
        }

        for(int i = 1; i < n - 1; i++) {
            if(nums[i] > minLeft[i - 1] && nums[i] < maxRight[i + 1])
                return true;
        }

        return false;   
    }
}

  

方法二:贪心算法

有点快慢指针的意思,固定两个指针,让另一个指针移动,再与前两个指针进行比较

  • 时间复杂度:O(n),其中 nn 是数组 \textit{nums}nums 的长度。需要遍历数组一次。

  • 空间复杂度:O(1)。

优点:时间复杂度相比于上双向遍历会低一些

缺点:理解起来相比于双向遍历会难一些

class Solution {
    //贪心算法
    public boolean increasingTriplet(int[] nums) {
        int n = nums.length;

        int first = nums[0], second = Integer.MAX_VALUE;
        for(int i = 1; i < n; i++) {
            if(nums[i] > second) {
                return true;
            } else if(nums[i] > first) {
                second = nums[i];
            } else {
                first = nums[i];
            }
        }
        
        return false;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值