My Java Solution with Code comments


  • 0
    C

    public class Solution {

    public boolean increasingTriplet(int[] nums) {

        if (nums.length < 3)
        {
            return false;
        }
    
        int indexOne = 0, indexTwo, indexThree;
    
        while (indexOne < (nums.length - 2))
        {
            indexTwo = indexOne + 1;
            while ((indexTwo < nums.length) && (nums[indexOne] >= nums[indexTwo]))
            {
                indexOne = indexTwo;
                indexTwo++;
            }
    
            indexThree = indexTwo + 1;
            while (indexThree < nums.length)
            {
                if (nums[indexThree] > nums[indexTwo])
                {
                    return true;
                }
                else if (nums[indexThree] > nums[indexOne])
                {
                    indexTwo = indexThree;
                    indexThree++;
                }
                else
                {
                    indexThree++;
                }
            }
            indexOne++;
        }
        return false;
    }
    

    }


  • 0
    C

    Sorry, for the bad formatting, this is my first time posting here... pretty new to the site.
    The key with this problem is that while there are nested loops, they actually avoid o(n^2) time by increment the outer loop conditional inside the inner loops. The first internal loop finds a good starting indexOne and indexTwo, the next loop checks indexTwo against indexThree to see if it has found the triplet, or if indexThree is a better indexTwo, replaces indexTwo with index Three and continues.


Log in to reply
 

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