分治法
问题
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⌋的数。题目保证所给的数列都有这个数存在。
分治法解法
我们可以将整个数组分成两个部分,先分别筛选出这两部分中出现次数最多的数,记为x和y,如果x等于y,则就可以找到这个问题的答案了。如果x不等于y,那么此时需要遍历整个链表考察,并计算x和y出现的次数,取出出现次数最多的当为最终结果。
这个算法的复杂度T(n) = 2T(n/2) + O(n) = O(nlogn)。