-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountarray.java
45 lines (43 loc) · 1.24 KB
/
countarray.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
public class countarray {
public static void main(String[] args) {
int[] arr = { 1, 1, 2, 2, 2, 2, 3 };
int num = 4;
count(arr, num);
}
public static void count(int[] arr, int k) {
int count = 0;
int low = 0;
int high = arr.length - 1;
int lowbound = 0;
int highbound = -1;
while (low <= high) {
int mid = low + ((high - low) / 2);
// first occurence
if (arr[mid] == k) {
high = mid - 1;
lowbound = mid;
} else if (arr[mid] > k) {
high = mid - 1;
} else if (arr[mid] < k) {
low = mid + 1;
}
}
low = 0;
high = arr.length - 1;
while (low <= high) {
int mid = low + ((high - low) / 2);
if (arr[mid] == k) {
low = mid + 1;
highbound = mid;
} else if (arr[mid] < k) {
low = mid + 1;
} else if (arr[mid] > k) {
high = mid - 1;
}
}
System.out.println(lowbound);
System.out.println(highbound);
count = highbound - lowbound + 1;
System.out.println(count);
}
}