16. 3Sum Closest

1. Description

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

2. Example

Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

3. Constraints

  • 3 <= nums.length <= $10^3$
  • $-10^3$ <= nums[i] <= $10^3$
  • $-10^4$ <= target <= $10^4$

4. Solutions

My Accepted Solution

n = m_nums.size()
Time complexity: O($n^2$)
Space complexity: O(n)

class Solution 
{
public:
    // int threeSumClosest(vector<int>& nums, int target)
    int threeSumClosest(vector<int> &m_nums, int target) 
    {
        sort(m_nums.begin(), m_nums.end());
        
        int result = 20000; // -10^4 <= target <= 10^4, so this number is invalid enough
        for(int i = 0; i < m_nums.size(); i++)
        {
            for(int left = i+1, right = m_nums.size()-1; left < right; )
            {
                int sum = m_nums[i] + m_nums[left] + m_nums[right];
                
                if(sum == target) return target;
                
                if(abs(sum - target) < abs(result - target))
                    result = sum;
                
                if(sum < target)
                    left++;
                else
                    right--;
            }
        }
        
        return result;
    }
};
comments powered by Disqus