Increasing Triplet 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.

答案

dp解法(overkill)

class Solution {
    public boolean increasingTriplet(int[] nums) {
        // dp[i] = what is the length of the longest increasing subsequence that ends at i
        int[] dp = new int[nums.length];
        Arrays.fill(dp, 1);

        for(int i = 1; i < nums.length; i++) {
            for(int j = 0; j < i; j++) {
                if(nums[j] < nums[i]) {
                    if(dp[j] + 1 == 3) return true;
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }

            }
        }

        return false;
    }
}

O(n)解法
Iterate from left to right, maintain the minimum and second minimum numbers.
If you can find some number that is greater than the current minimum and the second minimum, there must be an increasing triplet subsequence.

class Solution {
    public boolean increasingTriplet(int[] nums) {
        int first = Integer.MAX_VALUE;
        int second = Integer.MAX_VALUE;
        for(int x : nums) {
            if(x <= first) first = x;
            else if(x <= second) second = x;
            else return true;
        }
        return false;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • 最后一期《火星情报局》上维维的提案是:用一个字总结自己的2016。我很认真的想了想,然后在这里写下这个字:忙。 回...
    戈壁泡泡阅读 3,276评论 0 1
  • 随着现代科技的进步,大多数人都喜欢看电子书,认为它方便快捷,随时随地地阅读,其载体通常是随身携带的手机。我们都知道...
    萧竺阅读 1,472评论 0 1

友情链接更多精彩内容