334. Increasing Triplet Subsequence

Problem:
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.

Analysis:
这种题也是刷出来的,自己根本不可能想出来。
Use two pointers, min and secMin (second minmum). Initialize them to Integer.MAX_VALUE. Update their values on the go. If n is greater than secMin, we know that there is a triplet. 

Keep in mind that, min updates before second min. If secMin is not max value then we know that min is not max value. 

43628
min4332
2minmaxmax66

When we reach 6, we can make sure there is a increasing order of size 6. 2 starts the new sequence.

Solution:

class Solution {
    public boolean increasingTriplet(int[] nums) {
        int min = Integer.MAX_VALUE, secMin = Integer.MAX_VALUE;
        for (int n: nums) {
            if (n <= min) {
                min = n;
            } else if (n <= secMin) {
                secMin = n;
            } else if (n > secMin) {
                return true;
            }
        }
        return false;
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List