-
Notifications
You must be signed in to change notification settings - Fork 0
/
13_TotalOccurance.cpp
74 lines (62 loc) · 1.46 KB
/
13_TotalOccurance.cpp
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
// Find the total occurance of the number/element in the sorted array.
// formula to be in this question is:(lastoccurance - firstoccurance )+1
#include <iostream>
using namespace std;
int firstoccur(int arr[], int size, int key)
{
int ans1=0;
int s=0;
int e=size-1;
int mid=s+(e-s)/2;
while (s<=e)
{
if (arr[mid]==key)
{
ans1=mid;
e=mid-1;
}
else if (key<arr[mid])
{
e=mid-1;
}
else if (key>arr[mid])
{
s=mid+1;
}
mid=s+(e-s)/2;
}
return ans1;
}
int lastoccur(int arr[], int size, int key)
{
int ans2=0;
int s=0;
int e=size-1;
int mid=s+(e-s)/2;
while (s<=e)
{
if (arr[mid]==key)
{
ans2=mid;
s=mid+1;
}
else if (key<arr[mid])
{
e=mid-1;
}
else if (key>arr[mid])
{
s=mid+1;
}
mid=s+(e-s)/2;
}
return ans2;
}
int main(){
int arr[7]={1,2,2,3,3,3,3};
int n1=firstoccur(arr,7,3);
int n2=lastoccur(arr,7,3);
int total=(n2-n1)+1;
cout<<"The total occurance of 3 is "<<total;
return 0;
}