LeetCode - Majority Element
Problem description
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.
Example 1:
1
2
Input: [3,2,3]
Output: 3
Example 2:
1
2
Input: [2,2,1,1,1,2,2]
Output: 2
Analysis
The first thought is to use sort and then the middle one would be the majority item.
1
2
3
4
5
6
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
return nums[nums.length / 2];
}
}
Another method is to use Boyer-Moore Voting Algorithm.
Note that the majority one is more than half of the total count. then we can divide all items into two groups. One is all the same and the other one is different than item in previous one.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
Integer candidate = null;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}
What to improve