LeetCode 169 Majority Element

Problem:

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 exists in the array.

Summary:

求数组中出现频率大于数组一半的数,默认数组不为空且此数存在。

Analysis:

1. 将数组由小到大排序,由于所求之数出现次数大于n/2,故排序后位于n/2的数必为所求数。

1 class Solution {
2 public:
3     int majorityElement(vector<int>& nums) {
4         sort(nums.begin(), nums.end());
5         int len = nums.size();
6         
7         return nums[len / 2];
8     }
9 };

2. Hash表记录数组中出现数字与出现次数的映射。

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int len = nums.size();
 5         unordered_map<int, int> m;
 6         
 7         for (int i = 0; i < len; i++) {
 8             m[nums[i]]++;
 9         }
10         
11         unordered_map<int, int> :: iterator it;
12         for (it = m.begin(); it != m.end(); it++) {
13             if (it->second > len / 2) {
14                 return it->first;
15             }
16         }
17         
18         return -1;
19     }
20 };

3. 摩尔投票法(Moore majority vote algorithm)

https://en.wikipedia.org/wiki/Boyer-Moore_majority_vote_algorithm

此方法需要O(n)的时间和O(1)的空间。首先将第一个数字假设为所求之数,将计数器设置为1。遍历数组,比较数组中的数和假设之数是否相等,若相等则计数器加1,否则减1。当计数器为0时,将当前遍历到的数字设为新的假设之数,计数器初始化为1。如此重复,直至数组遍历结束,当前假设的数字极为所求之数。

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int len = nums.size(), res = nums[0], cnt = 1;
 5         
 6         for (int i = 1; i < len; i++) {
 7             if (res == nums[i]) {
 8                 cnt++;
 9             }
10             else {
11                 cnt--;
12             }
13             
14             if (!cnt) {
15                 res = nums[i];
16                 cnt = 1;
17             }
18         }
19         
20         return res;
21     }
22 };

用此方法求解,若存在majority element则一定可以找到,若不存在也会返回一个结果,并不能判断是否存在有效值。

 4. 位操作法(Bit Manipulation)

假设数组中所有数都是不超过32位的二进制数,那么对于每一位,计算数组中所有数在这一位上的值,若超过一半的数在这一位上值为1,则majority element在这一位上值为1,否则为0。

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) {
 4         int len = nums.size();
 5         int bits[32] = {0}, res = 0;
 6         
 7         for (int i = 0; i < 32; i++) {
 8             int cnt = 0;
 9             for (int j = 0; j < len; j++) {
10                 if ((nums[j] >> i) & 1) {
11                     cnt++;
12                 }
13             }
14             
15             if (cnt > len / 2) {
16                 res |= (1 << i);
17             }
18         }
19         
20         return res;
21     }
22 };
原文地址:https://www.cnblogs.com/VickyWang/p/6010590.html