题目描述
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.
算法分类:分而治之
解题思路
题目的意思很好理解,就是在一个数组中,找到出现次数大于一半的那个元素。并且假设数组非空,一定存在这个元素。
解这个题目有很经典的算法,即将每两个不同元素配对删除,最后剩下的就是该目标元素。这样只需要遍历一遍所有的元素即可,O(n)的线性时间复杂度。
刚开始在想这个问题和分治算法有什么关系,后来明白每删除一对元素,就相当于生成一个新的子数组,在该子数组中,目标元素仍是出现次数最多且大于一半的。这样不断删除,不断生成子数组。在实现上,引入一个记录次数的值times,times的值初始化为0,每当times重新变为0时,就相当于更新目标元素。删除元素并不是实际地将数组中的元素删掉,而是移动下标。
代码如下,包括了我的测试函数,运行时间19ms。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int majorityElement(vector<int>& nums) {
int result = 0;
int times = 0;
for(int i = 0; i<nums.size(); i++){
if (times==0) {
result=nums[i];
times++;
}
else{
if (nums[i]==result) {
times++;
}
else{
times--;
}
}
}
return result;
}
};
int main(){
Solution my;
vector<int> v;
for (int i=0 ; i<4; i++) {
v.push_back(1);
}
v.push_back(2);
v.push_back(3);
cout << my.majorityElement(v) << endl;
return 0;
}