# 关小刷刷题02——Leetcode 169. Majority Element 方法2和3

## 题目

169. Majority Element 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.

## 方法2

```class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int>temp;
for(int i=0; i<nums.size(); i++)
{
temp[nums[i]]++;
}
int number=temp.begin()->first;
int count=temp.begin()->second;
for(auto it=temp.begin(); it!=temp.end(); it++)
{
if(it->second>count)
{
number=it->first;
count=it->second;
}
}
return number;
}};```

```class Solution {
public:
int majorityElement(vector<int>& nums) {
map<int, int>temp;
for(int x:nums)
{
if (++temp[x]>nums.size()/2)
{
return x;
}
}
}
};```

## 方法3

```class Solution {
public:
int majorityElement(vector<int>& nums) {
int count=1;
int value=nums[0];
for(int i=1; i<nums.size(); i++)
{
if(count==0)
{
value= nums[i];
count++;
}
else
{
if(value==nums[i])
count++;
else
count--;
}
}
return value;
}
};```

0 条评论

## 相关文章

21260

37060

### 3522: [Poi2014]Hotel

3522: [Poi2014]Hotel Time Limit: 20 Sec  Memory Limit: 128 MB Submit: 253  Solve...

24960

### NOIP复习内容

https://www.luogu.org/problemnew/lists?name=GSS&orderitem=pid&tag=&content=0&typ...

18520

9210

35050

11730

30130

29580

30680