forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1.java
More file actions
52 lines (43 loc) ยท 1.74 KB
/
1.java
File metadata and controls
52 lines (43 loc) ยท 1.74 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
import java.util.*;
public class Main {
public static int lowerBound(int[] arr, int target, int start, int end) {
while (start < end) {
int mid = (start + end) / 2;
if (arr[mid] >= target) end = mid;
else start = mid + 1;
}
return end;
}
public static int upperBound(int[] arr, int target, int start, int end) {
while (start < end) {
int mid = (start + end) / 2;
if (arr[mid] > target) end = mid;
else start = mid + 1;
}
return end;
}
// ๊ฐ์ด [left_value, right_value]์ธ ๋ฐ์ดํฐ์ ๊ฐ์๋ฅผ ๋ฐํํ๋ ํจ์
public static int countByRange(int[] arr, int leftValue, int rightValue) {
// ์ ์: lowerBound์ upperBound๋ end ๋ณ์์ ๊ฐ์ ๋ฐฐ์ด์ ๊ธธ์ด๋ก ์ค์
int rightIndex = upperBound(arr, rightValue, 0, arr.length);
int leftIndex = lowerBound(arr, leftValue, 0, arr.length);
return rightIndex - leftIndex;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// ๋ฐ์ดํฐ์ ๊ฐ์ N, ์ฐพ๊ณ ์ ํ๋ ๊ฐ x ์
๋ ฅ๋ฐ๊ธฐ
int n = sc.nextInt();
int x = sc.nextInt();
// ์ ์ฒด ๋ฐ์ดํฐ ์
๋ ฅ๋ฐ๊ธฐ
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
// ๊ฐ์ด [x, x] ๋ฒ์์ ์๋ ๋ฐ์ดํฐ์ ๊ฐ์ ๊ณ์ฐ
int cnt = countByRange(arr, x, x);
// ๊ฐ์ด x์ธ ์์๊ฐ ์กด์ฌํ์ง ์๋๋ค๋ฉด
if (cnt == 0) System.out.println(-1);
// ๊ฐ์ด x์ธ ์์๊ฐ ์กด์ฌํ๋ค๋ฉด
else System.out.println(cnt);
}
}