LeetCode ---- 递增的三元子序列

本文介绍了一个算法问题:如何在一个未排序的数组中查找是否存在长度为3的递增子序列。该问题要求算法的时间复杂度为O(n),空间复杂度为O(1)。文章给出了具体的实现代码,并通过示例展示了算法的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

正式的数学表达如下:

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

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

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

public class IncreasingTriplet {

    @Test
    public void increasingTripletTest() {
        Assert.assertTrue(increasingTriplet(new int[]{1,2,3,4,5}));
        Assert.assertFalse(increasingTriplet(new int[]{5,4,3,2,1}));
        Assert.assertTrue(increasingTriplet(new int[]{2,1,5,0,4,6}));
    }

    public boolean increasingTriplet(int[] nums) {
        if (nums == null || nums.length == 0) {
            return false;
        }

        for (int i = 1; i < nums.length - 1; i++) {
            int finalI = i;
            if (Arrays.stream(Arrays.copyOfRange(nums, 0, i)).anyMatch(i1 -> i1 < nums[finalI])
                    && Arrays.stream(Arrays.copyOfRange(nums, i+1, nums.length)).anyMatch(i2 -> i2 > nums[finalI])) {
                return true;
            }
        }

        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值