第二周:[LeetCode]169. Majority Element

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


方法一:分治法: 将数组拆成两半, 分别找出前一半的众数和后一半的众数,若这两个众数相等,则全局众数就为改数,若不相等,则出现次数较多的众数为全局众数。时间复杂度为T(n) = T(n/2) + 2n = O(n log n).


class Solution {
public:
    int majorityElement(vector<int>& nums) {
        return divide_compare(nums,0,nums.size()-1);
    }
    int divide_compare(vector<int>& nums,int left,int right){
        if (left == right)
            return nums[left];
        int mid = left + (right - left)/2;
        int left_m = divide_compare(nums, left, mid);
        int right_m = divide_compare(nums, mid+1, right);
        if (left_m == right_m)
            return left_m;
        int left_m_count = count(nums.begin()+left,nums.begin()+right+1,left_m);
        int right_m_count = count(nums.begin()+left, nums.begin()+right+1, right_m);
        return left_m_count > right_m_count ? left_m: right_m;
    }
}; 

方法二:Moore投票算法(相当于简单实现的分治法): 维护一个当前的候选众数和一个初始为0的计数器。遍历数组时,当前值为x,如果计数器是0, 将候选众数置为x,并将计数器加一,如果计数器非0, 若x与候选众数相等,计数器加1,否则计数器减1(相当于不同的数互相抵消)。遍历完数组后, 当前的候选众数就是所求众数。时间复杂度 = O(n)。


    int majorityElement(vector<int>& nums) {
         int i,candidate=nums[0],count=1;
        for(i=1; i<nums.size();i++){
            if(count == 0){
                candidate = nums[i];
                count++;
                continue;
            }
            if(candidate == nums[i])
               count ++;
            else
               count --;
        }
        return candidate;
    }
}; 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值