Skip to content

Commit 35e0946

Browse files
authored
Create 3SumClosest.java
1 parent 7f34974 commit 35e0946

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

TwoPointer/3SumClosest.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//LeetCode 16. 3Sum Closest
2+
//Question - https://leetcode.com/problems/3sum-closest/
3+
4+
class Solution {
5+
public int threeSumClosest(int[] nums, int target) {
6+
int n = nums.length;
7+
Arrays.sort(nums);
8+
int res = nums[0] + nums[1] + nums[n-1];
9+
10+
for(int i = 0 ; i < n - 2 ; i++){
11+
if(i > 0 && nums[i] == nums[i-1]) continue;
12+
13+
int low = i+1;
14+
int high = n-1;
15+
16+
while(low < high){
17+
int sum = nums[i] + nums[low] + nums[high];
18+
if(Math.abs(sum - target) < Math.abs(res - target)){
19+
res = sum;
20+
}
21+
if(sum < target) low++;
22+
else high--;
23+
}
24+
}
25+
26+
return res;
27+
}
28+
}

0 commit comments

Comments
 (0)