Advertisement
1988coder

334. Increasing Triplet Subsequence

Jan 2nd, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. /**
  2.  * Refer:
  3.  * https://leetcode.com/problems/increasing-triplet-subsequence/discuss/79004/Concise-Java-solution-with-comments.
  4.  *
  5.  * Time Complexity: O(N)
  6.  *
  7.  * Space Complexity: O(1)
  8.  *
  9.  * N = Length of the input array.
  10.  */
  11. class Solution {
  12.     public boolean increasingTriplet(int[] nums) {
  13.         if (nums == null || nums.length < 3) {
  14.             return false;
  15.         }
  16.  
  17.         int c1 = Integer.MAX_VALUE;
  18.         int c2 = Integer.MAX_VALUE;
  19.  
  20.         for (int num : nums) {
  21.             if (num <= c1) {
  22.                 // update c1 if num is smaller than both c1 & c2.
  23.                 c1 = num;
  24.             } else if (num <= c2) {
  25.                 // update c2 only if num is greater than c1 but smaller than c2.
  26.                 c2 = num;
  27.             } else {
  28.                 // return true if found a number bigger than both c1 & c2.
  29.                 return true;
  30.             }
  31.         }
  32.  
  33.         return false;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement