-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberOfOccurrances.java
47 lines (41 loc) · 1.16 KB
/
NumberOfOccurrances.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
public class Solution {
static int findFirstOccurrance(int arr[], int n, int x) {
int low = 0, high = n - 1;
int idx = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
idx = mid;
high = mid - 1;
} else if (arr[mid] > x) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return idx;
}
static int findLastOccurrance(int arr[], int n, int x) {
int low = 0, high = n - 1;
int idx = -1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x) {
idx = mid;
low = mid + 1;
} else if (arr[mid] > x) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return idx;
}
public static int count(int arr[], int n, int x) {
//Your code goes here
int fo = findFirstOccurrance(arr, n, x);
if (fo == -1) return 0;
int so = findLastOccurrance(arr, n, x);
return so - fo + 1;
}
}