题目如下:
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.
分析如下:
居然几年前的一道baidu面试题也出现在leetcode上了,而且其实也来自几年前的《编程之美》中的找水王那到题目。这道题目的思路直接摘抄自官网:
Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
If the counter is 0, we set the current candidate to x and the counter to 1.
If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O(n).
我的代码:
//90ms
class Solution {
public:
int majorityElement(vector<int> &num) {
if (num.size() == 0) return 0;
int count = 1;
int majority_number = num[0];
for (int i = 1; i < num.size(); ++i) {
if (num[i] == majority_number) {
count++;
} else if (count == 0) {
majority_number = num[i];
}else{
count--;
}
}
return majority_number;
}
};写完之后,发现这道题目还有官方的解答,里面个思路还挺有意思,用到了bit运算,虽然对这道题目而言,不一定合适,但是思路挺有意思。
Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority
number’s ith bit must be the one bit that has the greater count.

本文深入分析了在数组中查找出现次数超过一半的元素的算法,包括Moore投票算法及位运算方法。详细解释了算法原理、实现方式,并附上代码实例。
850

被折叠的 条评论
为什么被折叠?



