-
Notifications
You must be signed in to change notification settings - Fork 0
/
Number_of_occurence_of_each_element_array_using_binary_Search.java
86 lines (66 loc) · 1.87 KB
/
Number_of_occurence_of_each_element_array_using_binary_Search.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.util.*;
public class Mainad {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
int q = input.nextInt();
for (int i = 0; i < q; i++) {
int x = input.nextInt();
int max = max(arr, n, x);
int min = min(arr, n, x);
if (min == 10000000 || max ==-1) {
System.out.println(-1);
}else{
System.out.println(max-min+1);
}
}
}
public static int min(int[] arr, int n, int x) {
int low = 0;
int high = n - 1;
int min = 10000000;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
min = mid;
low = low;
high = mid - 1;
}
if (arr[mid] > x) {
low = low;
high = mid - 1;
}
if (arr[mid] < x) {
high = high;
low = mid + 1;
}
}
return min;
}
public static int max(int[] arr, int n, int x) {
int low = 0;
int high = n - 1;
int max = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
max = mid;
low = mid + 1;
high = high;
}
if (arr[mid] > x) {
low = low;
high = mid - 1;
}
if (arr[mid] < x) {
high = high;
low = mid + 1;
}
}
return max;
}
}