You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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).
0 commit comments