Thursday, October 19, 2017

334. 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.

Solution:
Use two variables num1 and num2 to keep track current increasing subsequence. keep num1 < num2, If we find any element that is greater than num2, which means we found an increasing subsequence of length 3. If we find a number that is between num1 and num2, we update num2 to current number which make the third element easier to achieve. If we find a number is less then num1, update num1 as we can lower num2 and the third element thereafter. 

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

No comments:

Post a Comment