(Java) LeetCode 334. Increasing Triplet Subsequence —— 递增的三元子序列 LeetCode 300. Longest Increasing Subsequence —— 最长上升子序列

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should:

Return true if there exists  i, j, k 
such that  arr[i] <  arr[j] <  arr[k] given 0 ≤  i <  j <  k ≤  n-1 else return false.

Your algorithm should run in O(n) time complexity and O(1) space complexity.

Examples:
Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],
return false.


这道题和LeetCode 300. Longest Increasing Subsequence —— 最长上升子序列其实是一样的,只是增加了时间和空间复杂度的限制。其实因为只是判断是否有三元递增序列,那么当list中的元素达到三个,就可以返回ture,并且每次寻找替换元素的时候只是在两个之中选个大的,所以所谓的二项搜索其实也是只用了常数级的时间。所以其实基于第300题稍作修改就可以得到可以通过的代码。

优化的话其实就是把修改的过程翻译过来,设置两个变量num1,num2,初始设为最大值。遍历数组,如果有比num1小的,就把num1换成那个元素,如果有比num1大且比num2小的,把num2换掉,这两步其实是在模拟第300题中元素的替换。最后,当存在比num1和num2都大的数,那么就可以直接返回true了,这一步相当于模拟list.size() == 3。


Java

class Solution {
    public boolean increasingTriplet(int[] nums) {
        int num1 = Integer.MAX_VALUE, num2 = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++)
        {
            if (nums[i] < num1)                        num1 = nums[i];
            else if (nums[i] > num1 && nums[i] < num2) num2 = nums[i];
            else if (nums[i] > num2)                   return true;
        }
        return false;
    }
}

猜你喜欢

转载自www.cnblogs.com/tengdai/p/9245769.html