-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path016_ThreeSumClosest16.java
113 lines (94 loc) · 3.58 KB
/
016_ThreeSumClosest16.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int diff = Integer.MAX_VALUE;
for (int i = 0; i < nums.length; i++) {
int left = i + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (Math.abs(target - sum) < Math.abs(diff)) {
diff = target - sum;
}
if (sum > target) {
right--;
}
else {
left++;
}
}
}
return (target-diff);
}
}
****************************************************************************************
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int ans=Integer.MAX_VALUE;
for(int i=0;i<nums.length-1;i++)
{
int j=i+1;
int k=nums.length-1;
while(j<k)
{
if(Math.abs(target-(nums[i]+nums[j]+nums[k]))<Math.abs(ans))
ans=target-(nums[i]+nums[j]+nums[k]);
if((nums[i]+nums[j]+nums[k])<target) j++;
else k--;
}
}
return target-ans;
}
}
***************************************************************************************
class Solution {
public int threeSumClosest(int[] nums, int target) {
// sort array asc
Arrays.sort(nums);
// closed value to the target
int closest = Integer.MAX_VALUE;
// here we will store the result value
int result = 0;
// iterate from start to the end.
// 'curr' is one of the pointers
for(int curr = 0; curr < nums.length - 1; curr ++) {
// find the other values in an area between current pointer and the end
int start = curr + 1;
int end = nums.length - 1;
// iterate before two pointers meet each other
while(start != end) {
// our three pointers
int v1 = nums[start];
int v2 = nums[curr];
int v3 = nums[end];
// just a summ of all of pointers
int sum = v1 + v2 + v3;
// if we found exact value (suit for regular 3Sum)
if(sum == target) {
return sum;
}
// if the summ is higher than target move 'end' pointer to make the next summ lower (as far as we used sorted array)
if(sum > target) {
end--;
}
// if sum is too low than move start pointer to increase the value of the next sum
if(sum < target) {
start++;
}
// difference between 'target' and current 'sum'
int sumDif = 0;
// keep in mind that target can be below zero
// keep diff value as a positive as far as we're looking for the closest value from both size from the 'target'
if(target > 0) sumDif = Math.abs(target - sum);
else sumDif = Math.abs(sum - target);
// store result
if(sumDif < closest) {
closest = sumDif;
result = sum;
}
}
}
return result;
}
}