声明:原题目转载自LeetCode,解答部分为原创
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 exist in the array.
Solution:
思路:采用分治算法的思想,对于数组nums,将其一分为二,分别求出左半部分和右半部分的主元素及其出现次数,通过比较两者的出现次数,次数多的为整个数组nums的主元素。能够使用这种方法的关键在于,主元素的出现次数超过了⌊ n/2 ⌋,这确保了左右主元素至少有一个与整个数组的主元素相同,且其在该半部分的出现次数一定大于另一部分主元素的出现次数(数学方法易证)。相反,若是出现次数不超过⌊ n/2 ⌋,即使刚好达到⌊ n/2 ⌋,该解法不适用。例如,数组{1,1,1,2,2,2,2,2,2,3,3,3},左半部分为{1,1,1,2,2,2},右半部分为{2,2,2,3,3,3},无法确定主元素。另外,该解法与数组是否有序无关。
代码如下:
#include
#include
using namespace std;
class Solution {
public:
int majorityElement(vector
& nums) {
return find_majority(nums, 0, nums.size() - 1);
}
private:
int num_of_n(vector
& nums, int left, int right, int n)
{
int count = 0;
for(int i = left ; i <= right ; i ++)
{
if(nums[i] == n)
count ++;
}
return count;
}
int find_majority(vector
& nums, int left, int right) { if(left == right) return nums[left]; int mid = (left + right) / 2; int left_majority = find_majority(nums, left, mid); int left_num = num_of_n(nums, left, mid, left_majority); int right_majority = find_majority(nums, mid + 1, right); int right_num = num_of_n(nums, mid + 1, right, right_majority); if(left_num > right_num) return left_majority; else return right_majority; } }; int main() { Solution text_1; vector
nums; nums.push_back(1); nums.push_back(1); nums.push_back(2); nums.push_back(2); nums.push_back(2); nums.push_back(2); nums.push_back(2); nums.push_back(2); nums.push_back(3); nums.push_back(3); cout << text_1.majorityElement(nums) << endl; return 0; }