您的位置:首页 > 其它

LeetCode 169. Majority Element

2017-03-17 20:36 417 查看
题目:

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.

Credits:

Special thanks to @ts for adding this problem and creating all test cases.
思路:
给定一个数组,有n个数 ,找出其中的一个出现次数大于n/2的数。

有一个比较笨的方法,用nums_new来记录不同的数,对应的fre来

并且fre的空间还有浪费,水平暂时只到这里,但是成功Accepted~

代码:

class Solution {
public:
int majorityElement(vector<int>& nums) {
vector<int> nums_new;//记录nums中出现的不一样的数
vector<int> fre(nums.size());//记录与nums_new对应索引的那个数出现的次数,
nums_new.push_back(nums[0]);//将第一个数push_back
fre[0] = 1;//第一个数出现次数记1
for (int i = 1; i<nums.size(); ++i){//从第二个数开始循环到最后一个
int flag = 0;//用来标记这个数是否已经出现过,如果出现过,则flag=1
for (int j = 0; j<nums_new.size(); ++j){
if (nums[i] == nums_new[j]){//遍历nums_new,如果相等,则当前nums_new[j]对应的fre[j]+1
fre[j] += 1;
flag = 1;
}
}
if (flag == 0){//如果这个数没出现过,即flag==0,将这个数push_back,对应的fre[index]+1
nums_new.push_back(nums[i]);
fre[nums_new.size() - 1] += 1;
}
}
for (int k = 0; k<fre.size(); ++k){
if (fre[k]>(nums.size() / 2)){//遍历fre,找出出现次数大于n/2的数并返回
return nums_new[k];
break;
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: