美文网首页
Majority Element

Majority Element

作者: BigBig_Fish | 来源:发表于2017-07-03 08:39 被阅读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.

因为众数的出现次数大于二分之一,所以排序后肯定在中间的位置。
时间复杂度O(nlog n),空间复杂度O(1)

代码

int majorityElement(vector<int>& nums) {
        if (nums.size() == 1) {
            return nums[0];
        }
        sort(nums.begin(), nums.end());
        int len=nums.size();
        int mid=len/2;
        if (len %2 != 0) {
            return nums[mid];
        }else {
            if (nums[0] == nums[mid]){return nums[mid];}
            else return nums[mid+1];
        }
    }

机智方法

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int major, counts = 0, n = nums.size();
        for (int i = 0; i < n; i++) {
            if (!counts) {
                major = nums[i];
                counts = 1;
            }
            else counts += (nums[i] == major) ? 1 : -1;
        }
        return major;
    }
};

hash方法

出现次数大于n/2的数

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];
    }
};

随机数方法

感觉这个有点看脸,如果一直落在非众数上就很尴尬了

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        srand(unsigned(time(NULL)));
        while (true) {
            int idx = rand() % n;
            int candidate = nums[idx];
            int counts = 0; 
            for (int i = 0; i < n; i++)
                if (nums[i] == candidate)
                    counts++; 
            if (counts > n / 2) return candidate;
        }
    }
};

相关文章

网友评论

      本文标题:Majority Element

      本文链接:https://www.haomeiwen.com/subject/ldkacxtx.html