-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathmajorityElement.cpp
113 lines (97 loc) · 2.43 KB
/
majorityElement.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
int count;
Node *left;
Node *right;
};
void printBinaryTree(Node* p)
{
if(p)
{
printBinaryTree(p->left);
cout << "\t" << p->data << " count = " << p->count;
printBinaryTree(p->right);
}
}
int majorityElement(int a[], int size)
{
Node* p =NULL;
Node* q =NULL;
Node *head;
q = new Node();
q->left=NULL;
q->right=NULL;
q->data=a[0];
q->count=1;
head = q;
int flag = 0;
for(int i=1;i<size;i++)
{
p = head;
// cout<< "head = " << head->data;
// cout << "\n" << a[i];
int value = a[i];
while(true)
{
if(p->data == value)
{
int cnt = p->count;
cnt = cnt + 1;
if (cnt > (size/2))
{
cout << "Majority Element = " << a[i];
flag = 1;
break;
}
p->count = cnt;
break;
}
else if(value < p->data)
{
if(p->left)
p = p->left;
else
{
/* code */
Node *new_node = new Node();
new_node->left = NULL;
new_node->right = NULL;
new_node->data = value;
new_node->count= 1;
p->left=new_node;
break;
}
}
else if(value > p->data)
{
if(p->right)
p = p->right;
else
{
/* code */
Node *new_node = new Node();
new_node->left = NULL;
new_node->right = NULL;
new_node->data = value;
new_node->count= 1;
p->right=new_node;
break;
}
}
}
if (flag == 1)
break;
}
// printBinaryTree(head);
// your code here
return 0;
}
int main()
{
int arr[]={3,1,3,3,2};
majorityElement(arr , 5);
}