您的位置:首页 > 其它

LeetCode OJ刷题历程——Majority Element

2016-04-03 22:04 309 查看
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.

以上为题目要求,下面贴出代码:

class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
if(nums.size() == 1)
return nums[0];
int length = nums.size()/2 == 0?nums.size()/2 : nums.size()/2 +1;
for(int i = 0;i<length;i++)
if(nums[i] == nums[i+length-1])
return nums[i];
}
};
40ms

class Solution {
public:
int majorityElement(vector<int>& nums) {
stack<int>s;
for(auto n : nums){
if(s.empty() || n == s.top())
s.push(n);
else
s.pop();
}
return s.top();
}
};
24ms

class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
int index = nums[0];
int count = 1;
for(int i = 1;i<nums.size();i++){
if(index == nums[i])
count++;
else{
if(count > nums.size()/2)
return index;
else{
index = nums[i];
count == 1;
}
}
}
return index;
}
};
40ms

其中第三种方法比较容易想到,下面分析第一、二种方法

第一种对nums进行排序,因为如果是众数的话,其个数必定大于nums.size()的一半,所以如果nums[i] == nums[i+length/2 -1],那必定是众数

第二种是利用栈来进行判断,遇到不一样的数就进行弹栈操作,一样的入栈操作,如果不是众数,那么必定有多余其个数的数与之不同,那么栈中必定不会保留此数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: