forked from architsingla13/InterviewBit-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountElements.java
More file actions
52 lines (41 loc) · 1017 Bytes
/
CountElements.java
File metadata and controls
52 lines (41 loc) · 1017 Bytes
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
package BinarySearch;
import java.util.List;
/**
* Author - archit.s
* Date - 02/10/18
* Time - 10:06 AM
*/
public class CountElements {
int bSearch(List<Integer> A, boolean searchFirst, int B){
int low = 0;
int high = A.size()-1;
int result = -1;
while(low <= high){
int mid = low + (high - low)/2;
if(A.get(mid) == B){
result = mid;
if(searchFirst){
high = mid - 1;
}
else{
low = mid + 1;
}
}
else if(A.get(mid) > B){
high = mid - 1;
}
else{
low = mid + 1;
}
}
return result;
}
public int findCount(final List<Integer> A, int B) {
int left = bSearch(A,true,B);
int right = bSearch(A,false,B);
if(left == -1){
return 0;
}
return right-left + 1;
}
}