forked from ShreyaDhir/HacktoberFest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
3SumClosest.java
68 lines (55 loc) · 1.81 KB
/
3SumClosest.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import static java.lang.Math.abs;
import java.util.*;
class 3SumClosest
{
// Function to return the sum of a
// triplet which is closest to x
static int solution(Vector<Integer> arr, int x)
{
// Sort the array
Collections.sort(arr);
// To store the closets sum
int closestSum = Integer.MAX_VALUE;
// Fix the smallest number among
// the three integers
for (int i = 0; i < arr.size() - 2; i++)
{
// Two pointers initially pointing at
// the last and the element
// next to the fixed element
int ptr1 = i + 1, ptr2 = arr.size() - 1;
// While there could be more pairs to check
while (ptr1 < ptr2)
{
// Calculate the sum of the current triplet
int sum = arr.get(i) + arr.get(ptr1) + arr.get(ptr2);
// If the sum is more closer than
// the current closest sum
if (abs(x - sum) < abs(x - closestSum))
{
closestSum = sum;
}
// If sum is greater then x then decrement
// the second pointer to get a smaller sum
if (sum > x)
{
ptr2--;
}
// Else increment the first pointer
// to get a larger sum
else
{
ptr1++;
}
}
}
// Return the closest sum found
return closestSum;
}
public static void main(String[] args)
{
Vector arr = new Vector(Arrays.asList( -1, 2, 1, -4 ));
int x = 1;
System.out.println(solution(arr, x));
}
}