Majority Element
Given an array of sizen, 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.
1. Hashmap
时间复杂度: O(n), 空间复杂度: O(n)
2. 排序:将数组排序,因为多数的元素超过一半,因此排序后中间的元素必定是要求的多数元素
O(nlogn)
3. Majority Vote Algorithm
“投票算法”,设定两个变量candidate和count。candidate保存当前可能的候选众数,count保存该候选众数的出现次数。
遍历数组num。
如果当前的数字e与候选众数candidate相同,则将计数count + 1
否则,如果当前的候选众数candidate为空,或者count为0,则将候选众数candidate的值置为e,并将计数count置为1。
否则,将计数count - 1
如果存在数字e出现频率超过半数,那么数组中最后剩下的就只有e,最终留下的候选众数candidate即为最终答案。
以上算法时间复杂度为O(n),空间复杂度为O(1)
Last updated
Was this helpful?