问题描述:一个数组中,寻找出现次数大于数组长度一半的元素。假设这个元素一定存在。
解决:可以使用map来存储数据,key为元素的值,value为元素出现的次数。这种方式比较容易想到,是可行的。但是有一种更好的算法叫做Moore's voting。
它的思想是:数组中每出现一对不同的元素就将这对元素从数组中删除,如果元素e出现次数过半,那么最后数组中肯定只剩下e这种元素。当然,并不是
数组中最后剩余的元素一定是出现次数过半的,只是因为本题中已经假设了过半元素一定存在,那么我们只需要把这个元素找出来即可。majority指定为
第0个元素,count初始值为1,当遇到与majority相同元素时,count++,遇到不同元素时,count--。当count=0时,表明前面的元素成对不同需要删去
(一半是majority,一半是其他元素),我们这里并不是还要做删除数组元素的操作,而是将majority重新指定为当前的元素,count重新置1,对剩余
的数组元素做相同操作(其实就是原问题的子问题)。
/*
* 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.
*/
public class MajorityElement {
public int majorityElement(int[] nums) {
int count=1;
int majority = nums[0];
for(int i=1; i<nums.length; i++) {
if(nums[i]==majority)
count++;
else
count--;
if(count==0) {
majority = nums[i];
count++;
}
}
return majority;
}
}