-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfindClosestSum.java
More file actions
52 lines (41 loc) · 1.13 KB
/
findClosestSum.java
File metadata and controls
52 lines (41 loc) · 1.13 KB
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
class Solution {
public static int findClosest(int n, int k, int[] arr) {
// code here
int low = 0;
int high = n - 1;
if (k <= arr[0]) {
return arr[0];
}
if (k >= arr[n - 1]) {
return arr[n - 1];
}
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == k) {
return arr[mid];
}
if (k < arr[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
int closest;
if (low < n && high >= 0) {
int diffLow = Math.abs(arr[low] - k);
int diffHigh = Math.abs(arr[high] - k);
if (diffLow < diffHigh) {
closest = arr[low];
} else if (diffLow > diffHigh) {
closest = arr[high];
} else {
closest = Math.max(arr[low], arr[high]);
}
} else if (low < n) {
closest = arr[low];
} else {
closest = arr[high];
}
return closest;
}
}