Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions 16. 3Sum Closest/solution.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#include <math.h>


void insertion_sort(int arr[], int n)
{
for (int i = 1; i < n; ++i)
{
int key = arr[i];
int j = i - 1;

while ((j >= 0) && (arr[j] > key))
{
arr[j + 1] = arr[j];
j = j - 1;
}

arr[j + 1] = key;
}
}

/**
* Given a list of numbers, nums
* We need to find 3 integers at distinct indices in nums
* Such that their sum either equals or is the closest to 'target'
*/
int threeSumClosest(int* nums, int numsSize, int target)
{
insertion_sort(nums, numsSize);
int closest = nums[0] + nums[1] + nums[2];

for (int i = 0; i < numsSize - 2; ++i)
{
int left = i + 1;
int right = numsSize - 1;

while (left < right)
{
int curr_sum = nums[i] + nums[left] + nums[right];
if (abs(curr_sum - target) < abs(closest - target))
closest = curr_sum;

if (curr_sum < target)
left += 1;
else if (curr_sum > target)
right -= 1;
else
return curr_sum;
}
}

return closest;
}
30 changes: 30 additions & 0 deletions 16. 3Sum Closest/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from typing import List


class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
"""
Given a list of numbers, nums
We need to find 3 integers at distinct indices in nums
Such that their sum either equals or is the closest to 'target'
"""
nums.sort()
closest = sum(nums[:3])

for i in range(len(nums) - 2):
left = i + 1
right = len(nums) - 1

while left < right:
current_sum = nums[i] + nums[left] + nums[right]
if abs(current_sum - target) < abs(closest - target):
closest = current_sum

if current_sum < target:
left += 1
elif current_sum > target:
right -= 1
else:
return current_sum

return closest