1. 程式人生 > >Majority Element

Majority Element

this edit span appears exist 真的 class HR ray

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