-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcountOccurrence.java
More file actions
83 lines (76 loc) · 2.12 KB
/
countOccurrence.java
File metadata and controls
83 lines (76 loc) · 2.12 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package algorithm.search;
import java.util.HashMap;
import java.util.Map;
/**
* The type Count occurrence.
*/
public class countOccurrence {
/**
* Count int.
*
* @param arr the arr
* @param key the key
* @return the int
*/
public static int count(int[] arr , int key){
Map<Integer,Integer> map = new HashMap();
for(int i =0;i<arr.length;i++){
if(map.containsKey(arr[i])){
map.put(arr[i],map.get(arr[i])+1);
}else{
map.put(arr[i],1);
}
}
return map.get(key);
}
/**
* Get frequency int.
*
* @param arr the arr
* @param key the key
* @return the int
*/
public static int getFrequency(int[] arr,int key){
int arrSize =arr.length;
int start =0, end = arrSize-1, mid , result =-1;
//Modify binary search to find left occurrence
while(start<end){
mid = (start + end) / 2;
if(arr[mid]==key){
result = mid;
end = mid-1;
}else if(arr[mid]>key){
end = mid-1;
}else if(arr[mid]<key){
start=mid+1;
}
}
//Modify binary search to find ri8 occurrence
int start1 = 0, end1 = arrSize - 1, mid1, result1 = -1;
while (start1 <= end1) {
mid1 = (start1 + end1) / 2;
if (arr[mid1] == key) {
result1 = mid1;
start1 = mid1 + 1;
} else if (arr[mid1] > key) {
end1 = mid1 - 1;
} else if (arr[mid1] < key) {
start1 = mid1 + 1;
}
}
//Get difference of ri8 and left
if (result == -1 || result1 == -1)
return (result1 - result);
return (result1 - result + 1);
}
/**
* Main.
*
* @param args the args
*/
public static void main(String[] args){
int arr[] = {-5,-3,0,1,3,3,3,3,4,5};
int key = 3;
System.out.println("The key \""+ key + "\" occurs " + getFrequency(arr, key) + " times in the Array.");
}
}