Skip to content

Commit 138a1ce

Browse files
Three Sum Closest: Accepted
1 parent db08fe9 commit 138a1ce

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,3 +158,4 @@ My accepted leetcode solutions to some of the common interview problems.
158158
- [Longest Substring Witout Repeats](problems/src/two_pointers/LongestSubstringWitoutRepeats.java) (Medium)
159159
- [Three Sum](problems/src/two_pointers/ThreeSum.java) (Medium)
160160
- [Trapping Rain Water](problems/src/two_pointers/TrappingRainWater.java) (Hard)
161+
- [3Sum Closest](problems/src/two_pointers/ThreeSumClosest.java) (Hard)
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package two_pointers;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Created by gouthamvidyapradhan on 13/06/2017.
7+
* Accepted
8+
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
9+
10+
For example, given array S = {-1 2 1 -4}, and>
11+
12+
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
13+
*/
14+
public class ThreeSumClosest {
15+
16+
public static void main(String[] args) {
17+
int[] a = {-1, 2, 1, -4};
18+
System.out.println(new ThreeSumClosest().threeSumClosest(a, 1));
19+
}
20+
21+
public int threeSumClosest(int[] a, int target) {
22+
Arrays.sort(a);
23+
int min = Integer.MAX_VALUE, ans = -1;
24+
for(int i = 0, l = a.length; i < l - 2; i ++) {
25+
if(i == 0 || ! (a[i] == a[i - 1])) {
26+
int j = i + 1, k = l - 1;
27+
while(k > j) {
28+
if(j != i + 1 && (a[j] == a[j - 1])) {
29+
j ++;
30+
continue;
31+
}
32+
int sum = a[i] + a[j] + a[k];
33+
if(sum < target) {
34+
int diff = Math.abs(sum - target);
35+
if(diff < min) {
36+
min = diff;
37+
ans = sum;
38+
}
39+
j++;
40+
}
41+
else if(sum > target) {
42+
int diff = Math.abs(sum - target);
43+
if(diff < min) {
44+
min = diff;
45+
ans = sum;
46+
}
47+
k--;
48+
}
49+
else{
50+
return sum;
51+
}
52+
}
53+
}
54+
}
55+
return ans;
56+
}
57+
}

0 commit comments

Comments
 (0)