/*
* Leetcode169. Majority Element
* Funtion: Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
* Example:
* Author: LKJ
* Date:2016/7/22
* Hint:求主元素,在数组中出现超过n/2次,,,,中位数一定是主元素
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
int len = nums.size();
int x = nums[len/2];
int cnt = 0;
for(vector<int>::iterator it = nums.begin(); it != nums.end(); it++){
if(*it == x){
cnt++;
}
}
if(cnt >= (len/2)){
return x;
}else{
return 0;
}
}
};
int main(){
int myarr[5] = {1,1,1,5,6};
vector<int> myin(myarr,myarr+5);
int myout;
Solution SA;
myout = SA.majorityElement(myin);
cout << myout << endl;
return 0;
}
LeetCode 简单操作 | 169. Majority Element
最新推荐文章于 2024-06-06 13:14:27 发布
本文介绍了一个解决LeetCode 169题目的方法,该题目要求找到数组中的主元素,即出现次数超过数组长度一半的元素。通过先排序数组再统计指定元素的出现次数来确定主元素。
595

被折叠的 条评论
为什么被折叠?



