Like 3sum closest using two pointers C++ implementation using O(n^2)


  • -1
    Z
    int threeSumSmaller(vector<int>& nums, int target) {
        if(nums.size()<3)
            return 0;
        int result=0;
        sort(nums.begin(), nums.end());
        for(int i=0; i<nums.size()-2; i++)
        {
            int left=i+1, right=nums.size()-1;
            while(left<right)
            {
                int curSum=nums[i]+nums[left]+nums[right];
                if(curSum>=target)
                {
                    right--;
                }
                else
                {
                    result += (right-left);
                    left++;
                }
            }
        }
        return result;
    }

Log in to reply
 

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