Skip to content

Commit 383370d

Browse files
Majority elements
Signed-off-by: Leo Ma <begeekmyfriend@gmail.com>
1 parent fc02ac6 commit 383370d

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed

229_majority_element_ii/Makefile

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test majority.c

229_majority_element_ii/majority.c

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
static int *majorityElement(int* nums, int numsSize, int *returnSize)
5+
{
6+
int i, m = -1, n = -1, cm = 0, cn = 0;
7+
for (i = 0; i < numsSize; i++) {
8+
if (m == nums[i]) {
9+
cm++;
10+
} else if (n == nums[i]) {
11+
cn++;
12+
} else if (cm == 0) {
13+
m = nums[i];
14+
cm++;
15+
} else if (cn == 0) {
16+
n = nums[i];
17+
cn++;
18+
} else {
19+
cm--;
20+
cn--;
21+
}
22+
}
23+
24+
cm = 0;
25+
cn = 0;
26+
for (i = 0; i < numsSize; i++) {
27+
if (nums[i] == m) {
28+
cm++;
29+
} else if (nums[i] == n) {
30+
cn++;
31+
}
32+
}
33+
34+
int count = 0;
35+
int *results = malloc(2 * sizeof(int));
36+
if (cm > numsSize / 3) {
37+
results[count++] = m;
38+
}
39+
if (cn > numsSize / 3) {
40+
results[count++] = n;
41+
}
42+
43+
*returnSize = count;
44+
return results;
45+
}
46+
47+
int main(int argc, char **argv)
48+
{
49+
if (argc < 2) {
50+
fprintf(stderr, "Usage: ./test target n1 n2...\n");
51+
exit(-1);
52+
}
53+
54+
int i, size = argc - 1;
55+
int *nums = malloc(size * sizeof(int));
56+
for (i = 0; i < size; i++) {
57+
nums[i] = atoi(argv[i + 1]);
58+
}
59+
60+
int count = 0;
61+
int *results = majorityElement(nums, size, &count);
62+
for (i = 0; i < count; i++) {
63+
printf("%d ", results[i]);
64+
}
65+
printf("\n");
66+
return 0;
67+
}

0 commit comments

Comments
 (0)