[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>





阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/denny851108/article/details/51536396
文章标签: leetcode easy
个人分类: leetcode
上一篇[leetcode] 217. Contains Duplicate
下一篇[leetcode] 344. Reverse String
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭