-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCeil the floor
67 lines (51 loc) · 1.65 KB
/
Ceil the floor
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
//Ceil the floor
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-- > 0) {
int x = Integer.parseInt(br.readLine());
String[] input = br.readLine().split(" ");
int[] arr = new int[input.length];
for(int i = 0; i < input.length; i++) {
arr[i] = Integer.parseInt(input[i]);
}
Solution ob = new Solution();
int[] ans = ob.getFloorAndCeil(x, arr);
System.out.println(ans[0] + " " + ans[1]);
}
}
}
class Solution {
public int[] getFloorAndCeil(int x, int[] arr) {
int[] ans = new int[2];
int left = 0, right = arr.length - 1;
Arrays.sort(arr);
Arrays.fill(ans, -1);
while(left <= right) {
int mid = (left + right) / 2;
if(arr[mid] < x) {
ans[0] = arr[mid];
if(mid == arr.length - 1) {
break;
}
left = mid + 1;
}
else if(arr[mid] > x) {
ans[1] = arr[mid];
if(mid == 0) {
break;
}
right = mid - 1;
}
else {
ans[0] = x;
ans[1] = x;
break;
}
}
return ans;
}
}