-
Notifications
You must be signed in to change notification settings - Fork 1
/
TotalOccurrence.java
66 lines (62 loc) · 2.08 KB
/
TotalOccurrence.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
Given a target integer T and an integer array A sorted in ascending order, Find the total number of occurrences of T in A.
Examples
A = {1, 2, 3, 4, 5}, T = 3, return 1
A = {1, 2, 2, 2, 3}, T = 2, return 3
A = {1, 2, 2, 2, 3}, T = 4, return 0
Corner Cases
What if A is null? We should return 0 in this case.
*/
public class TotalOccurrence {
// Solution 2 starts here
// TC: O(log(n) + count)
// SC: O(1)
public int totalOccurrence2(int[] a, int T) {
if (a == null || a.length == 0) return 0;
int l = 0, r = a.length - 1, m = 0;
while (l <= r) {
m = l + (r - l) / 2;
if (a[m] == T) break;
else if (a[m] < T) l = m + 1;
else r = m - 1;
}
int count = 0;
for (l = m; l >= 0 && a[l] == T; l--) count++;
for (r = m + 1; r < a.length && a[r] == T; r++) count++;
return count;
}
// Solution 2 ends here
// Solution 1 starts here
// TC: O(2*log(n))
// SC: O(1)
public int totalOccurrence(int[] a, int T) {
if (a == null || a.length == 0) return 0;
int l = firstOccur(a, T);
if (l == -1) return 0; // T do not exist
return lastOccur(a, T) - l + 1;
}
private int firstOccur(int[] a, int T) {
int l = 0, r = a.length - 1;
while (l < r - 1) {
int m = l + (r - l) / 2;
if (a[m] < T) l = m;
else r = m;
}
return a[l] == T ? l : a[r] == T ? r : -1;
}
private int lastOccur(int[] a, int T) {
int l = 0, r = a.length - 1;
while (l < r - 1) {
int m = l + (r - l) / 2;
if (a[m] <= T) l = m;
else r = m;
}
return a[r] == T ? r : a[l] == T ? l : -1;
}
// Solution 1 ends here
public static void main(String[] args) {
TotalOccurrence to = new TotalOccurrence();
System.out.println(to.totalOccurrence2(new int[]{1, 2, 2, 2, 4, 5, 8, 13, 13}, 13) == 2);
System.out.println(to.totalOccurrence(new int[]{1, 2, 2, 2, 4, 5, 8, 13, 13}, 13) == 2);
}
}