1ms Java solution with explanation


  • 8

    ----------------- Updated Solution (1ms) -----------------

    While I found a more concise way: initialize the two variables as Integer.MAX_VALUE, then no need to maintain the counter c.

    public boolean increasingTriplet(int[] nums) {
        if(nums.length<=2) return false;
        int a=Integer.MAX_VALUE, b=a;
        for(int x:nums){
          if(x<a) a=x;
          else if(x>a && x<b) b=x;
          else if(x>a && x>b) return true;
        }
        return false;
    }
    

    ----------------- Initial Solution (2ms) ----------------------

    The main idea is to use two variables tmp[2] to keep the most smallest two elements.

    When meeting a element:

    If smaller than tmp[0], update tmp[0].

    If larger than tmp[0] while smaller than tmp[1], update tmp[1].

    If larger than tmp[1], return true.

    public class Solution {
      public boolean increasingTriplet(int[] nums) {
        if(nums.length<=2) return false;
        int[] tmp = new int[2];
        int c=0;
        tmp[0]=nums[0];
        for(int x:nums)
          if(c==0){
            if(x>tmp[c]) tmp[++c] = x;
            else if(x<=tmp[c]) tmp[c] = x;
          }
          else{
            if(x>tmp[c]) return true;
            else{
              if(x<=tmp[0]) tmp[0]=x;
              else if(x<tmp[1]) tmp[1]=x;
            }
          }
          return false;
        }
      }

  • 0
    J

    thanks for sharing your solution.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.