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

给定一个未排序的数组,请判断这个数组中是否存在长度为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;
    }
}

猜你喜欢

转载自blog.csdn.net/ydonghao2/article/details/80405411