AC solution with explanation


  • 0
    U
    public class Solution {
    public int threeSumSmaller(int[] nums, int target) {
        Arrays.sort(nums);
        int res=0;
        for(int i=0;i<nums.length;i++){
            int p1=i+1<nums.length? i+1:nums.length-1;
            int p2=nums.length-1;
            while(p1<p2){
                int sum= nums[i]+nums[p1]+nums[p2];
                if(sum<target){
                    res+=(p2-p1);// once we find a sum which is smaller than target  then [p1,p1+1] [p1,p1+2]....[p1,p2] all of them should be inclued in the res;
                    p1++;
                }
                else
                    p2--;
            }
            
        }
        return res;
        
    }
    

    }


Log in to reply
 

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