Java two variable Solution, Explanation.


  • 1
    S

    Because we only need to find out three increasing numbers.
    We only have to keep track of two numbers. One is the smallest
    we have come up with and another is the smallest second number
    we have met. In the following code, "one" is the smallest and "two"
    is the smallest second number. If there is any number larger than
    "two" return true.

    public class Solution {
        public boolean increasingTriplet(int[] nums) {
            if(nums==null||nums.length<3) return false;
            int one = Integer.MAX_VALUE;
            int two = Integer.MAX_VALUE;
            for(int num:nums){
                if(num>one){
                    if(num>two){
                        return true;
                    }else{
                        two = num;
                    }
                }else{
                    one = num;
                }
            }
            return false;
        }
    }

  • 0

    Fails for input [-2147483648,0,1].


  • 0
    S

    Thank you for pointing it out, I just changed the default value to Integer.MAX_VALUE. I think that might work.


  • 0

    Yes, I think it's correct now. You have two unnecessary branches, btw, that can simply be deleted.


  • 0
    S

    Thank you for your advise, it looks quite succinct now!


Log in to reply
 

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