3Sum Closest - Array - Medium - LeetCode
💻 coding

3Sum Closest - Array - Medium - LeetCode

1 min read 167 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to find three integers in an array whose sum is closest to a given target.
  • 2The solution involves sorting the array and using a two-pointer technique to find the closest sum.
  • 3The algorithm has a time complexity of O(n^2) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to find three integers in an array whose sum is closest to a given target."

3Sum Closest - Array - Medium - LeetCode

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.

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).

Constraints:

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

public class Solution {
 public int ThreeSumClosest(int[] nums, int target) {
 Array.Sort(nums);
 int minDiff = int.MaxValue;
 int minSum = 0;
 for(int i=0;i<nums.Length-2;i++){
 for(int j=i+1, k=nums.Length-1; j<k;){
 int sum = nums[i]+ nums[j]+ nums[k]; 
 int diff = Math.Abs(sum-target); 
 if(minDiff>diff){
 minDiff = diff;
 minSum = sum;
 }
 if(sum > target){
 k--;
 }
 else if(sum < target){
 j++;
 }
 else{
 // if sum is equal to target
 return target;
 }
 }
 }
 
 return minSum;
 }
}

Time Complexity: O(n^2+nlogn) = O(n^2)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 23 October 2020 · 1 min read · 167 words

Part of AskGif Blog · coding

You might also like