Skip to content

Commit c0a6b0d

Browse files
author
applewjg
committed
Majority Element
Change-Id: I57339ea91629b95bd318d8df6b126fcb2d911f1c
1 parent 22d7e88 commit c0a6b0d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

MajorityElement.h

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 14, 2014
4+
Problem: ZigZag Conversion
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/majority-element/
7+
Notes:
8+
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
9+
10+
You may assume that the array is non-empty and the majority element always exist in the array.
11+
12+
Solution: Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
13+
If the counter is 0, we set the current candidate to x and the counter to 1.
14+
If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
15+
After one pass, the current candidate is the majority element. Runtime complexity = O(n).
16+
*/
17+
18+
class Solution {
19+
public:
20+
int majorityElement(vector<int> &num) {
21+
int n = num.size();
22+
if (n == 0) return 0;
23+
if (n == 1) return num[0];
24+
int cur = num[0], cnt = 1;
25+
for (int i = 1; i < num.size(); ++i) {
26+
if (cnt == 0) {
27+
cur = num[i];
28+
++cnt;
29+
continue;
30+
}
31+
if (cur == num[i]) ++cnt;
32+
else --cnt;
33+
}
34+
return cur;
35+
}
36+
};

0 commit comments

Comments
 (0)