题目英文描述:
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.
题目中文描述:
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
代码:(先排序,然后去中间值)(时间O(nlogn)):
class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[nums.size()/2];
}
};
代码:(哈希)(时间O(n),空间O(n)):
class Solution {
public:
int majorityElement(vector<int>& nums) {
int majority, max = 0;
unordered_map<int, int> map;
for(int i = 0; i < nums.size(); ++i) {
++map[nums[i]];
if(map[nums[i]] > max) {
max = map[nums[i]];
majority = nums[i];
}
}
return majority;
}
};
代码:(投票)(时间O(n),空间O(1)):
class Solution {
public:
int majorityElement(vector<int>& nums) {
int candidate = -1, count = 0;
for(int i = 0; i< nums.size(); ++i) {
if(count == 0) candidate = nums[i];
if(candidate == nums[i]) ++count;
else --count;
}
return candidate;
}
};