169. Majority Element
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.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
解题思路
题目是要求寻找数组中出现次数最多的那个数,这里可以采用分治算法的思想。即将数组分成两个部分,在两个部分中分别找出出现次数最多的那个数字,如果两个部分返回的数相同,那么这个数就是所求答案。如果返回的数不同,那需要在两个分组中遍历两个数字出现的次数加以比较,出现次数多的即为所求。
代码如下:
class Solution {
public:
int majorityElement(vector<int>& nums) {
return majority(nums, 0, nums.size() - 1);
}
int majority(vector<int>& nums, int left, int right) {
if(left == right) {
return nums[left];
}
int mid = left + (right - left) / 2;
int lm = majority(nums, left, mid);
int rm = majority(nums, mid + 1, right);
if(lm == rm) return lm;
else {
int count_lm = count(nums.begin() + left, nums.begin() + right + 1, lm);
int count_rm = count(nums.begin() + left, nums.begin() + right + 1, rm);
return count_lm > count_rm ? lm : rm;
}
}
};