AdSense

Sunday, June 5, 2016

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.

Initialize x1 and x2 to max value. Traverse the array, if num is less than x1, set x1 to num. Else if x1 < num < x2, set x2 to num. Else if num > x2, return true. The idea is to keep a sequence of triplet, and reduce the differences among the three numbers until find a solution.




public boolean increasingTriplet(int[] nums) {
        if (nums == null || nums.length < 3)
            return false;
        int x1 = Integer.MAX_VALUE, x2 = Integer.MAX_VALUE;
        for(int num : nums) {
            if (num < x1)
                x1 = num;
            else if (x1 < num && num < x2)
                x2 = num;
            else if (num > x2)
                return true;
        }
        return false;
    }


The second solution is also an accepted one, but it's too complicated and requires extra space.

public boolean increasingTriplet(int[] nums) {
        if (nums == null || nums.length < 3)
            return false;
        TreeMap<Integer, List<Integer>> map = new TreeMap<>();
        map.put(nums[0], new ArrayList<>());
        for (int i = 1; i < nums.length; i++){
            int num = nums[i];
            if (map.floorKey(num) != null) {
                for (Integer key : map.headMap(num).keySet()){
                    if (key == num)
                        continue;
                    List<Integer> values = map.get(key);
                    if (values.size() > 0 && num <= values.get(0))
                        values.clear();
                    values.add(num);
                    if (values.size() == 2)
                        return true;
                }

            }
            if (!map.containsKey(num))
                map.put(num, new ArrayList<>());
        }
        return false;
    }

No comments:

Post a Comment