MrainW's Home

All things come to those who wait!

0%

LeetCode 16. 3Sum Closest

Question

Given an integer array nums of length n 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.

https://leetcode.com/problems/3sum-closest/

  • Solution1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length == 0) return target;
Arrays.sort(nums);
int delta = nums[0] + nums[1] + nums[2] - target;
for (int i = 0; i < nums.length - 2; i++){
int start = i + 1;
int end = nums.length - 1;
while (start < end) {
int newDelta = nums[i] + nums[start] + nums[end] - target;
if (newDelta == 0) return target;
if (Math.abs(newDelta) < Math.abs(delta)) delta = newDelta;
if (newDelta < 0) start++;
else end--;
}
}
return target + delta;
}
}

Complexity:

Time complexity: O( n^2)

Space complexity: O(n)

Welcome to my other publishing channels