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.
题目来自https://leetcode.com/problems/majority-element/description/
思路解析
首先这道题是在LeetCode的分而治之小标题找到的,所以我只考虑用分而治之的方法去解答。其实我的解法有点类似归并排序的思路。首先最大数量的数字超过1/2,假设数组有2n个数字,平分为a,b两组,目标结果为r,数量为n。找到a组中最大的数量的数字x,b组最大数量的数字y。如果x等于y,那么他们就是r。否则,如果x的数量小于y,那么y就是r;如果x的数量大于y,x就是r;如果两者的数量相同,那么
xy所在的组的数量最少,它就是r。同理把a,b再分别分两组,共四组,再分别分。。。。直到分成2n组。
代码
class Solution {
public:
int majorityElement(vector<int>& nums) {
int result[2] = {0, 0}; //存储最大的数及其个数
int begin = 0; //给定数组的开始
int end = nums.size()-1; // 给定数组的最后一个元素
find(nums, begin, end, result);
return result[0];
}
//函数目的:通过递归找到最大的数
void find(vector<int> &nums,int begin, int end,int* result) {
if (begin == end) { //递归到最底层
result[0]=nums[begin];
result[1] = 1;
}
else {
int mid = (begin + end)/2;
find(nums, begin, mid, result);// 对数组左边进行递归
int flag = result[0];
int flagNum = result[1];
find(nums, mid + 1, end, result); //对数组右边进行递归
if (result[0] == flag) { //左边与右边最大的数相同,就把他们的数量相加
result[1] += flagNum;
}
//左边右边的数不相同
else if (result[1] > flagNum) { //右边结果的数量大于左边,则取右边且加上该数在左边的量
int term = find_num(nums, begin, mid, result[0]);
result[1] += term;
}
else if (result[1] < flagNum) { //左边结果的数量大于右边,则取左边且加上该数在右边的量
int term = find_num(nums, mid + 1, end, flag);
result[0] = flag;
result[1] += term;
}
else if (result[1] == flagNum) { //两边的结果的量相同
if ((mid + begin) > (end - mid - 1)) { //数组左边的数的数量多与右边,则取右边的结果为结果
int term = find_num(nums, begin, mid, result[0]);
result[1] += term;
}
else { //否则取左边的结果为结果
int term = find_num(nums, mid + 1, end, flag);
result[0] = flag;
result[1] += term;
}
}
}
}
//找到给定的数字在规定的范围内的数量
int find_num(vector<int> &nums, int begin, int end, int target) {
int num = 0;
for (int i = begin; i <= end; i++) {
if (nums[i] == target) {
num++;
}
}
return num;
}
};