Simple code c++


  • 3
    R

    here is my code which is just similar to the code for previous problem 3Sum . but here we don't need to take consideration of duplicates.

    threeSumClosest

    int threeSumClosest(vector<int>& nums, int target) {
            sort(nums.begin(),nums.end());
            int n=nums.size(),ans;
            int min=INT_MAX;
            for(int i=0;i<n-2;i++){
                   int l=i+1, r= n-1;
                   while(l<r){
                       int sum =nums[i]+nums[l]+nums[r];
                       if(abs(sum-target)<min){  // updating the sum if sum  so far. is closest to target
                          min=abs(sum-target);
                          ans=sum;
                       }
                       if(sum<target) l++;        //
                       else if(sum>target)r--;
                       else {
                           return sum;  // we have sum equal to target which is closest so no need to check further 
                       }
                   }
            }
            return ans;
        }
    

    threeSum

    vector<vector<int>> threeSum(vector<int>& nums) {
            sort(nums.begin(),nums.end());
            int n=nums.size();
            vector<vector<int>> res;
            for(int i=0;i<n-2;i++){
                   if(i>0 && (nums[i]==nums[i-1]) )continue;   // to avoid duplicates
                   int l=i+1, r= n-1;
                   while(l<r){
                       int sum =nums[i]+nums[l]+nums[r];
    
                       if(sum<0) l++;
                       else if(sum>0)r--;
                       else {
                           res.push_back(vector<int>{nums[i],nums[l],nums[r]});
                           while(l+1<r && nums[l]==nums[l+1])l++;    // to avoid duplicates
                           while(l<r-1 && nums[r]==nums[r-1]) r--;     // to avoid duplicates
                           l++; r--;
                       }
                   }
            }
    
            return res;
        }

  • 0
    M

    thanks for share . this solution helped me a lot .


  • 0
    L

    thanks for share. it is very clear now.


  • 0
    H

    For the equal case, why not just return target. No breaking loops requires


  • 0
    R

    oops !! thanks for pointing it . I have made the appropriate changes .


Log in to reply
 

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