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.
这道题主要考察了majority vote Algorithm,该算法的时间复杂度为o(n),空间复杂度为o(1),与哈希方法时间复杂度相同,比哈希空间复杂度小,适合处理元素较大的情况,但该算法只适合于已知有元素个数大于1/2的情况,不能用于找最多元素的个数(不能保证最多元素个数大于整体的1/2)
算法思想:flag=第一个元素,count=1,从第二个开始,如果num[i]==flag那么count+1,如果不等且count!=0时,count-1,如果count=0,则flag=num[i]。即flag所指元素后面的元素,如果与此元素相等,则计数器加1,如果不等就减1,直至计数器为0时就更换为目前的元素。
特殊情况如 ABACADA 加一次减一次直至flag=最后一个A为止,count=1。那么A即为所求元素。倘若没有最后的A,ABACAD,该算法则找不到最多的那个元素,即没有大于1/2的数。
Source
public class Solution {
public int majorityElement(int[] num) {
int flag = num[0];
int cnt = 1;
for(int i = 1; i < num.length; i++){
if(cnt == 0) flag = num[i];
if(num[i] != flag) cnt--;
else cnt++;
}
return flag;
}
}
Test
public static void main(String[] args){
int[] num = {2,3,5,2,2,3,4,2,2}; //注意数组初始化方式 int[] a = new int(n);
System.out.println(new Solution().majorityElement(num));
}