forked from lolosssss/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path169_majority_element.c
More file actions
44 lines (37 loc) · 914 Bytes
/
169_majority_element.c
File metadata and controls
44 lines (37 loc) · 914 Bytes
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
/**
* Description : Majority Element
* Given an array of size n, find the majority element. The
* majority element is the element that appears more than n/2
* times. You may assume that the array is non-empty and the
* majority element always exist in the array.
* Author : Evan Lau
* Date : 2016/03/27
*/
#include <stdio.h>
int majorityElement(int* nums, int numsSize)
{
int ret;
int count = 0;
for (int i = 0; i < numsSize; i++)
{
if (count == 0)
{
ret = nums[i];
}
if (ret == nums[i])
{
count++;
}
else
{
count--;
}
}
return ret;
}
int main(void)
{
int arr[] = {1, 4, 5, 1, 8, 5, 5, 5, 5, 5};
printf("The majority element of the array is %d\n", majorityElement(arr, 10));
return 0;
}