LeetCode[169. Majority Elemen] 难度[easy]

题目

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.
意思就是找出一个数组里面n个元素中出现次数大于n/2的元素
这道题可以有以下多种做法:
算法一:先排序,第n/2个元素就是要的结果,时间复杂度是O(nlogn)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        int *temp = new int[n];
        for(int i=0;i<n;++i)
            temp[i] = nums[i];
        sort(temp,temp+n);
        int result = temp[n/2];
        delete [] temp;
        return result;;
    }
};

算法二:使用map,把每个元素出现的次数记录下来,找出现次数大于n/2的元素,时间复杂度是O(nlogn)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        map<int,int> Map;
        for(int i=0; i<n; ++i)
            Map[nums[i]]++;
        for(int i=0; i<n; ++i)
            if(Map[nums[i]]>n/2)
                return nums[i];
        return 0;
    }
};

算法三:使用摩尔投票法,时间复杂度是O(n)

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

算法四:使用分治思想,把原来的数组分成两个小数组,若两个数字的Majority Element都知道了,则原来数组的Majority Element必定是这两个的其中一个,只要统计两个元素哪个出现次数多就可以找到,时间复杂度为O(nlogn)
(这里实现的时候有个小细节就是,向量nums要按引用传递,若按值传递会超时)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        return MajorityElement(nums,0,n-1);
    }
private:
    int MajorityElement(vector<int>& nums,int low,int high){
        if(low==high)   return nums[low];
        int mid = low + ((high-low) >> 1);
        int left = MajorityElement(nums,low,mid);
        int right = MajorityElement(nums,mid+1,high);
        if(left==right) return left;
        return count(nums.begin()+low,nums.begin()+high+1,left)>count(nums.begin()+low,nums.begin()+high+1,right)?left:right;
    }
};

算法五:这个算法比较巧妙,在数列中随机取一个数,统计这个数字出现的次数,若大于n/2则结果就是这个,若不是则重新取,由于所求元素在数组中出现次数很多,所以选中的几率大,平均2次就可以选中,算法时间复杂度为O(n)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n = nums.size();
        srand(time(0));
        while(true){
            int idx = rand()%n;
            if(count(nums.begin(),nums.begin()+n,nums[idx])>n/2)    
                return nums[idx];
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值