-
Notifications
You must be signed in to change notification settings - Fork 4
/
3.cpp
87 lines (73 loc) · 1.57 KB
/
3.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
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<iostream>
#include <bits/stdc++.h>
#include<math.h>
using namespace std;
// https://www.interviewbit.com/problems/n3-repeat-number/
bool checkMajority(vector<int> arr, int index)
{
long ele = arr[index];
int count=0;
for(long c: arr)
if(c==ele)
count++;
int brick = arr.size()/3;
if(count>=brick)
{
return true;
}
return false;
}
int repeatNumber(const vector<int> &arr)
{
int l = arr.size();
cout<<l<<endl;
int brick = l/3;
cout<<brick<<endl;
int majority1_index =0;
int majority2_index =0;
int count1=0;
int count2=0;
for(int i=0;i<l;i++)
{
if(arr[i]==arr[majority1_index])
{
count1++;
}
else if(arr[i]==arr[majority2_index])
{
count2++;
}
else if(count1==0)
{
majority1_index=i;
count1++;
}
else if(count2==0)
{
majority2_index = i;
count2++;
}
else
{
count1--;
count2--;
}
}
if (checkMajority(arr,majority1_index))
{
cout<<arr[majority1_index]<<endl;
cout<<arr[majority2_index]<<endl;
return arr[majority1_index];
}
else if(checkMajority(arr,majority2_index))
{
return arr[majority2_index];
}
return -1;
}
int main()
{
vector<int> arr{1,1,1,3,3,2,2,2};
cout<< repeatNumber(arr)<<endl;
return 0;
}