美文网首页
334. Increasing Triplet Subseque

334. Increasing Triplet Subseque

作者: 衣介书生 | 来源:发表于2018-04-11 20:52 被阅读13次

题目分析

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.

代码

class Solution {
    public boolean increasingTriplet(int[] nums) {
        int min = Integer.MAX_VALUE;
        int secondMin = Integer.MAX_VALUE;
        for(int num : nums) {
            // 先判断是不是等于或小于当前最小值
            if(num <= min) {
                min = num;
            // 再判断是不是等于或小于当前第二小的值
            } else if(num <= secondMin) {
                secondMin = num;
            // 判断第三大的值是否出现了
            } else {
                return true;
            }
        }
        return false;
    }
}

相关文章

网友评论

      本文标题:334. Increasing Triplet Subseque

      本文链接:https://www.haomeiwen.com/subject/tsazhftx.html