-
Notifications
You must be signed in to change notification settings - Fork 0
/
Number of occurrence
62 lines (49 loc) · 1.58 KB
/
Number of occurrence
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
//Number of occurrence
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tc = Integer.parseInt(br.readLine().trim());
while(tc-- > 0) {
String[] inputLine;
inputLine = br.readLine().trim().split(" ");
int n = Integer.parseInt(inputLine[0]);
int x = Integer.parseInt(inputLine[1]);
int[] arr = new int[n];
inputLine = br.readLine().trim().split(" ");
for(int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(inputLine[i]);
}
int ans = new Solution().count(arr, n, x);
System.out.println(ans);
}
}
}
class Solution {
int count(int[] arr, int n, int x) {
int count = 0, left = 0, right = n - 1;
while(left <= right) {
int mid = (left + right) / 2;
if(arr[mid] > x) {
right = mid - 1;
}
else if(arr[mid] < x) {
left = mid + 1;
}
else {
int i = mid - 1;
while(i >= 0 && arr[i] == x) {
i--;
count++;
}
while(mid < n && arr[mid] == x) {
mid++;
count++;
}
break;
}
}
return count;
}
}