Find the Element Appearing More Than Half the Time
Implement majorityElement
Given an array
nums of size n, return the majority element — the value that appears MORE THAN ⌊n/2⌋ times. It's guaranteed that a majority element always exists.
Counting each candidate's occurrences by rescanning the array works, but it repeats a lot of counting across candidates. The Boyer-Moore Voting AlgorithmBoyer-Moore Voting AlgorithmA single-pass technique for finding a majority element: treat every element as casting a vote for or against a running candidate, and whenever the vote count hits zero, adopt the next element as the new candidate. Because a true majority element can never be fully outvoted, whatever candidate survives to the end is the answer. answers this in one O(n) pass with O(1) space, by treating the scan as an election that the majority element can never lose.
Example 1:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Example 2:
Input: nums = [3,2,3]
Output: 3
Example 3:
Input: nums = [1]
Output: 1
+ 8 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 5 × 10⁴ - ●
-2³¹ ≤ nums[i] ≤ 2³¹ - 1 - ●
It is guaranteed nums always has a majority element.
nums =
[2, 2, 1, 1, 1, 2, 2]