Simple O(n2) JAVA solution


  • 0
    C
    public class Solution
    {
        public int threeSumSmaller(int[] nums, int target)
        {
            int count = 0;
            
            Arrays.sort(nums);
            
            int n = nums.length;
            
            for(int i = 0; i < n - 2; i++)
            {
                int newTarget = target - nums[i];
                
                int j = i + 1;
                
                int k  = n - 1;
                
                while(j < k)
                {
                    
                    while(j < k && nums[j] + nums[k] >= newTarget)
                    {
                        k--;
                    }
                    
                    if(j < k)
                    {
                        count += (k - j);
                        j++;
                    }
                }
                
            }
            
            return count;
        }
    }

Log in to reply
 

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