-
Notifications
You must be signed in to change notification settings - Fork 4
/
Majority_Element.c
84 lines (74 loc) · 1.52 KB
/
Majority_Element.c
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
/* A value in an array is a majority element if its frequency is greater than
(n/k) + 1. This program implements a linear time algorithm that solves the
problem. */
#include<stdio.h>
#include<stdlib.h>
int* majorEle(int arr[], int n, int k){
int *ans = (int*) calloc(k, sizeof(int)),
**bucket = (int**) malloc(sizeof(int*) * (k-1)),
la = 1, i, j;
for(i = 0; i < k-1; i++){
bucket[i] = (int*) calloc(2, sizeof(int));
}
for(i = 0; i < n; i++){
for(j = 0; j < k-1; j++){
if(bucket[j][0] == arr[i]){
bucket[j][1]++;
break;
}
}
if(j == k-1){
for(j = 0; j < k-1; j++){
if(!bucket[j][1]){
bucket[j][0] = arr[i];
bucket[j][1]++;
break;
}
}
if(j == k-1){
for(j = 0; j < k-1; j++){
bucket[j][1]--;
}
}
}
}
for(i = 0; i < k-1; i++){
bucket[i][1] = 0;
}
for(i = 0; i < n; i++){
for(j = la-1; j < k-1; j++){
if(arr[i] == bucket[j][0]){
bucket[j][1]++;
if(bucket[j][1] > (n/k)){
ans[la++] = bucket[j][0];
ans[0]++;
int *temp = bucket[j];
bucket[j] = bucket[la-2];
bucket[la-2] = temp;
}
break;
}
}
}
for(i = 0; i < k-1; i++){
free(bucket[i]);
}
free(bucket);
return ans;
}
int main(){
int k = 4, arr[] = {1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 9}, *ans = NULL, i;
int n = sizeof(arr)/sizeof(int);
ans = majorEle(arr, n, k);
if(!ans[0]){
printf("No majority element!");
}
else{
printf("Majority Elements: ");
for(i = 1; i<=ans[0]; i++){
printf("%d ", ans[i]);
}
}
printf("\n");
return 0;
}