We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 7f34974 commit 35e0946Copy full SHA for 35e0946
TwoPointer/3SumClosest.java
@@ -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