关闭

[leetcode] 169. Majority Element

标签: leetcodeeasy
176人阅读 评论(0) 收藏 举报
分类:

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>





0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9687次
    • 积分:632
    • 等级:
    • 排名:千里之外
    • 原创:31篇
    • 转载:150篇
    • 译文:0篇
    • 评论:0条
    文章分类