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的数组,找到数组中的 majority 元素,majority元素是在数组中出现次数大于 n/2 向下取整次的元素
你可以嘉定数组非空且 majority 元素总是存在
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
Solutions:
Python
(1)
'''
因为majority元素一定存在,那么只要将元素统计一下出现个数,然后按照统计的个数排序,第一个数一定是majority元素
'''
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dict0 = {}
for i in nums:
dict0[i] = dict0.get(i,0)+1
list0 = sorted(dict0.items(),key = lambda d:d[1],reverse = True)
return list0[0][0]
(2)
'''
将元素进行排序,nums[len(nums)//2]一定是majority,因为majority元素超过了1/2数组长度,排序后数组中间的元素一定是majority
'''
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)//2
nums[:] = sorted(nums,reverse = True)
return nums[length]
C++
(1)
class Solution {
public:
int majorityElement(vector<int>& nums) {
int length = floor(nums.size()/2);
sort(nums.begin(),nums.end());
return nums[length];
}
};
(2)
/*
首先用unordered_map对nums中的元素进行计数统计
然后创建一个pair<int,int>,用Map中出现次数元素对pair进行更新
pair中留存的是出现次数最大的元素和它的次数,由于majority一定存在
那么pair中存放的一定是majority元素
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int,int> Map;
pair<int,int> order = {0,0};
for (int i : nums){
Map[i] += 1;
}
for (pair<int,int>element : Map){
if (element.second > order.second){
order = element;
}
}
return order.first;
}
};
(3)
/*
这个是leetcode上最快的算法,他的思想是设置一个标志位x,用来记录nums中元素出现的次数
将nums中元素分为两部分,最少一半是majority元素,剩余的是其他元素,只有majority元素
可以保持x减不到0,即t在等于majority之后不会被更新掉,t = majority,返回t就可以了
*/
class Solution {
public:
int majorityElement(vector<int>& nums) {
int size = nums.size();
if(size==1) return nums[0];
int t = nums[0];
int x = 1;
for(int i=1;i<size;i++)
{
if(x==0)
{
t = nums[i];
}
if(t==nums[i])
x++;
else
x--;
}
return t;
}
};
C++中map按照values进行排序: