# [leetcode] 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.

Solution:

Idea: sort numbers and return (n/2)th element

class Solution {
public:
int majorityElement(vector<int>& nums) {
sort(nums.begin(), nums.end());
return nums[floor(nums.size()/2)];
}
};

Solution:

Idea: randomly select one element and check its appliance time in the array. It runs faster.

<span style="font-size:14px;">class Solution {
public:
int majorityElement(vector<int>& nums) {
srand(unsigned(time(NULL)));
int n = nums.size();
while(true){
int elem = nums[rand()%n];
int counter = 0;
for(int i=0; i<n; i++){
if(nums[i]==elem)
counter++;
}
if (counter > n/2)
return elem;
}

}
};</span>

Solution:

Idea: hash table by using unordered_map

<span style="font-size:14px;">class Solution {
public:
int majorityElement(vector<int>& nums) {
unordered_map<int, int> counter;
int n = nums.size();
int major;
for(int i=0; i<n; i++){
if(++counter[nums[i]]>n/2){
major = nums[i];
break;
}
}
return major;
}
};</span>

#### LeetCode169:Majority Element

2015-07-09 19:29:49

#### 【LeetCode-面试算法经典-Java实现】【169-Majority Element（主元素）】

2015-08-23 06:38:30

#### 169. Majority Element [easy] (Python)

2016-05-14 20:04:32

#### LeetCode169. Majority Element分治法

2016-09-21 00:07:18

#### [leetcode-169]Majority Element(java)

2015-08-23 11:05:36

#### LeetCode169——Majority Element

2015-01-15 11:11:26

#### leetcode【169 Majority Element】【Python】

2016-09-08 09:48:22

#### 169. Majority Element (python)

2016-10-30 16:08:15

#### [leetcode: Python]169. Majority Element

2017-05-12 11:52:28

#### 169. Majority Element 难度：Easy 类别：分治

2016-09-11 11:06:16