O(n2) time complexity java 2 pointers w explaination


  • 0
    B

    a, b, a and are triangle sides when a + b > c, a+c > b, and b+c > a. If a, b, c in ascending order then only thing needs to check is a+b < c.

    Sorting array helps reduce number of checks and can use 2 pointers. Same as 3sum problem.
    lo and hi pointer only visits nums elements once. For each lo increasing, hi doesn't need to be reset because if nums[i] + nums[lo] < nums[hi] then of course nums[i] + nums[lo+1] < nums[hi]. So when increase lo, hi should try to go further to the end of array.

        public int triangleNumber(int[] nums) {
            if (nums.length < 3)
                return 0;
            
            int count = 0;    
            Arrays.sort(nums);
            for (int i = 0; i < nums.length - 2; i ++){
                
                int lo = i + 1;
                int hi = lo;
                
                while(lo < nums.length - 1){
    
                    while(hi + 1 < nums.length && nums[hi + 1] < nums[i] + nums[lo])
                        hi++;
                    if (hi - lo > 0)
                        count += hi - lo;
                    
                    lo++;
                    
                }    
            }
                
            return count;
                
        }
    
    

  • 0
    Z

    @bellevue of course you meant a + b > c


  • 0
    B

    @zinking yes that's what i meant :)


Log in to reply
 

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