-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathCountOccurancesInSorted.java
More file actions
66 lines (60 loc) · 1.42 KB
/
CountOccurancesInSorted.java
File metadata and controls
66 lines (60 loc) · 1.42 KB
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
/**
*
* Ashish Patel
* e: ashishsushilPatel@gmail.com
* w: https://ashish.me
*
*/
class CountOccurancesInSorted {
static int firstOccurance(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while(start <= end){
int mid = (start+end)/2;
if(nums[mid] > target){
end = mid - 1;
} else if(nums[mid] < target){
start = mid + 1;
} else {
if(mid == 0 || nums[mid] != nums[mid - 1]){
return mid;
} else {
end = mid - 1;
}
}
}
return -1;
}
static int lastOccurance(int[] nums, int target) {
int start = 0;
int end = nums.length - 1;
while(start <= end){
int mid = (start + end)/2;
if(nums[mid] > target){
end = mid - 1;
} else if(nums[mid] < target){
start = mid + 1;
} else {
if(mid == nums.length - 1 || nums[mid] != nums[mid + 1]){
return mid;
} else {
start = mid + 1;
}
}
}
return -1;
}
static int countOccurance(int[] nums, int target) {
int first = firstOccurance((nums), target);
if(first == -1){
return 0;
} else {
return lastOccurance(nums, target) - first + 1;
}
}
public static void main(String[] args){
int[] nums = new int[] { 1, 4, 8, 34, 34, 34, 123, 123, 3466, 5687 };
int result = countOccurance(nums, 123);
System.out.println(result);
}
}