forked from ndb796/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path1.java
52 lines (43 loc) Β· 1.74 KB
/
1.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
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);
}
}