forked from GeeksforGeeks-VIT-Bhopal/GeekWeek-Local
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDay 4_Leetcode_1.java
More file actions
33 lines (30 loc) · 913 Bytes
/
Day 4_Leetcode_1.java
File metadata and controls
33 lines (30 loc) · 913 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
3Sum Closest-JAVA
public class ThreeSumClosest {
public int threeSumClosest(int[] nums, int target) {
// Sort the array
Arrays.sort(nums);
// Length of the array
int n = nums.length;
// Result
int closest = nums[0] + nums[1] + nums[n - 1];
// Loop for each element of the array
for (int i = 0; i < n - 2; i++) {
// Left and right pointers
int j = i + 1;
int k = n - 1;
// Loop for all other pairs
while (j < k) {
int sum = nums[i] + nums[j] + nums[k];
if (sum <= target) {
j++;
} else {
k--;
}
if (Math.abs(closest - target) > Math.abs(sum - target)) {
closest = sum;
}
}
}
return closest;
}
}