Simple Java Solution...Easy to understand!!!!


  • 25
    A
    public class Solution {
        public boolean increasingTriplet(int[] nums) {
            if (nums ==  null || nums.length < 3 ){
                return false;
            }
            int min = Integer.MAX_VALUE;
            int secondMin = Integer.MAX_VALUE;
            
            for (int i = 0; i < nums.length; i++){
                if (nums[i] <= min){
                    min = nums[i];
                }
                else if (nums[i] <= secondMin){
                    secondMin = nums[i];
                }
                else {
                    return true;
                }
            }
            return false;
        }
    }

  • 0

    I think this line is not necessary in this case when use the foreach loop :

    if (nums == null || nums.length < 3 ){return false;}


  • 0
    H

    can you tell me the process of thinking when you write the code? I am still puzzled about the principle of it. thanks!


  • 0
    A

    Since you have to find the 3 numbers in increasing order in a given array you have to traverse through the array starting from 0 index to the end of index while you maintain the min and second minimum value. That is exactly what is done.
    Here while traversing we are making sure that min index < second min Index


  • 1

    Please refer to Longest Increase Subsequence problem, this solution is just a particular case for the nlogn binary search algorithm.


  • 1
    F

    Yes, the border situations are not tested in this problem, but it's always a good habit to check all the possible cases.


  • 0
    H

    @ash1625 how about [8,9,1,12]? When 1 is set to min, the secondMin is still 9. So, you did not make sure that min index < second min Index. However, the result is correct.


Log in to reply
 

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