LeetCode169. Majority Element
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.
意思是找出数组中那个出现了超过n/2次的数。
我们可以这样想,如果这个数出现的次数超过了半数,每次从数组中删除一对不同的数,最后剩下的那些相同的数,一定会是我们需要的majority。做法是,一边计数,一边找候选的majority。假如我们现在已经有了一个候选的majority,接下来查看其后面的那个数,如果两个数相等,意味着majority的数量增加,于是计数要增加1,如果两个数不等,计数就要减一,相当于删去了一对不同的数,然后继续向后面查看。倘若有时计数为0了,意味着前面删去了若干对不同的数,没有多余的那个,也就是说,需要重现选取候选majority了。
这种算法的名字叫做
Moore’s Voting Algorithm,是一种解决这种问题的专门办法。