Example:
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).
Approach: We can sort the array and then can use 2 pointers approach.
Implementation in C#:
public int ThreeSumClosest(int[] nums, int target)
{
int diff = int.MaxValue, result = int.MaxValue;
if (nums == null && nums.Length < 3)
{
return result;
}
Array.Sort(nums);
for (int i = 0; i < nums.Length; ++i)
{
int low = i + 1, high = nums.Length - 1;
while(low < high)
{
int sum = nums[i] + nums[low] + nums[high];
if (diff > Math.Abs(target - sum))
{
diff = Math.Abs(target - sum);
result = sum;
if (diff == 0)
{
return result;
}
}
if (sum < target)
{
++low;
}
else
{
--high;
}
}
}
return result;
}
Complexity: O(n^2)
No comments:
Post a Comment