Problem
A majority element is an element that makes up more than half of the items in an array. Given a positive integers array, find the majority element. If there is no majority element, return -1. Do this in O(N) time and O(1) space.
Example
Example1:
Input: [1,2,5,9,5,9,5,5,5]
Output: 5
Example2:
Input: [3,2]
Output: -1
Example3:
Input: [2,2,1,1,1,2,2]
Output: 2
Solution
Java
Solution1 排序
class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int mid = nums[nums.length / 2];
int cnt = 0;
for(int j = 0; j < nums.length; j++) {
if(nums[j] == mid)
cnt++;
}
if(cnt > nums.length / 2)
return mid;
else
return -1;
}
}
Solution2 摩尔投票算法
class Solution {
public int majorityElement(int[] nums) {
int count = 1;
int candidate = nums[0];
for(int i = 1; i < nums.length; i++) {
if(nums[i] != candidate) {
if(count == 0) {
candidate = nums[i];
count++;
}
else
count--;
}
else
count++;
}
int times = 0;
for(int j = 0; j < nums.length; j++) {
if(nums[j] == candidate)
times++;
}
if(times > (nums.length / 2))
return candidate;
else
return -1;
}
}
思路
Solution1 排序
将数组排序后,中间的数据不一定是主要元素,但主要元素一定在中间。
所以再将中间值与数组中每个值进行比较,若相等,则计数cnt+1。如果cnt最后大于等于 n / 2,则说明中间值就是主要元素,否则数组无主要元素。
这种比较简单,很容易想,但是复杂度较高。
Solution2 摩尔投票算法
算法思想:
首先设置count和candidate两个变量。从数组第一个数据开始,candidate 初始化为 nums[0], count = 1。然后按顺序将数组元素与 candidate 比较,如果两数据相等,则 count++, candidate不变。如果两数据不等,则 count 减一。当 count == 0, 且待比较的数据与 candidate 不等时,candidate 修改为待比较的这个数据,count = 1。比到最后,如果存在主要元素的话,那么留下来的candidate就是主要元素了。
所以在最后要和排序算法一样,要遍历数组与candidate比较,若出现次数大于 n / 2,说明candidate就是主要元素。
性能明显提升