题目:
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.
提示:
此题此题推荐三种比较好的方法:
- 排序法(最简单):将数组排序,然后输出中位数;
- 随机方法:因为有大于50%的概率会一下子就随机抽中出现频率最大的数字,因此性能也算不错。具体方法就是在while循环中随机抽取一个数字,计算这个数字在数组中出现的次数,如果大于n/2次,那么就输出,不然的话就继续随机抽取下一个数字;
- Moore Voting方法(最稳定,效率也很好):这个算法的时间复杂度是O(n),空间复杂度是O(1),我觉得是解决此题的最佳方法。
代码:
排序法:
class Solution { public: int majorityElement(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums[nums.size() / 2]; } };
随机方法:
class Solution { public: int majorityElement(vector<int>& nums) { int n = nums.size(); srand(unsigned(time(NULL))); while (true) { int idx = rand() % n; int candidate = nums[idx]; int counts = 0; for (int i = 0; i < n; i++) if (nums[i] == candidate) counts++; if (counts > n / 2) return candidate; } } };
Moore Voting方法:
class Solution { public: int majorityElement(vector<int>& nums) { int major, counts = 0, n = nums.size(); for (int i = 0; i < n; i++) { if (!counts) { major = nums[i]; counts = 1; } else counts += (nums[i] == major) ? 1 : -1; } return major; } };