Majority Element

Posted jiadyang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

直接上代码吧

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) 
 4     {
 5         int n = nums.size();
 6         sort(nums.begin(), nums.end());
 7         int cnt = 0;
 8         int res = 0;
 9         for (int i = 0; i < n; ++i)
10         {
11             int s = count(nums.begin(), nums.end(), nums[i]);
12             if (cnt < s)
13             {
14                 cnt = s;
15                 res = nums[i];
16             }
17             i += s;
18         }    
19         return res;
20     }
21 };    

意思应该比较明了,就是不是很快速,也不简洁,看看其他大神的解答吧

这个哈希表应该能想到的呀~~~刷题比较少没有感觉~~~

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int, int> counts; 
        int n = nums.size();
        for (int i = 0; i < n; i++)
            if (++counts[nums[i]] > n / 2)
                return nums[i];
    }
};
用到了nth_element函数,既然是多于一半的数自然中间.
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        nth_element(nums.begin(), nums.begin() + nums.size() / 2, nums.end());
        return nums[nums.size() / 2];
    } 
};

既然用了上面这个函数,那么我为什么不直接sort就行了=_+, 真的太笨了。

 1 class Solution {
 2 public:
 3     int majorityElement(vector<int>& nums) 
 4     {
 5         int n = nums.size();
 6         
 7         sort(nums.begin(), nums.end());
 8         
 9         return nums[n/2];
10     }
11 };

先记这些吧~~~

以上是关于Majority Element的主要内容,如果未能解决你的问题,请参考以下文章

169. Majority Element

169. Majority Element@python

169. Majority Element

Leetcode 169. Majority Element

169. Majority Element

LeetCode169. Majority Element