169. Majority Element (divide and conquer)

题目描述:

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.

##算法分析:

根据题目可知,所给的vector中必然会出现一个majority element 的频数大于 n/2,而且是唯一的(不可能同时出现两个频数大于n/2的element),所以,可以通过哈希法(map),以键值对的方式,key记录element,而value记录element的频数,遍历vector,再从map中找出频数最高的element,这样一来其效率是O(n)+O(n/2),而其实我们可以在遍历vector的同时找出频数最高的element,因为一旦频数大于n/2的element出现即可停止遍历(majority element的唯一性)。

算法设计:

int majorityElement(vector<int>& nums) {
    map<int, int> buf;
    int size = nums.size();
    for(int i = 0;i < size; i++) {
        buf[nums[i]]++;
        if(buf[nums[i]] > size/2)
            return nums[i];
    }

}
###算法学习借鉴 个人分析:

假如vector中的element总数为 n = 2k+1,则majority element的频数 f 大于 n/2,即大于等于 k+1,假如 n = 2k, 一样的有 f 大于 n/2,即 f 大于等于k+1。因此,在一列数中,不管以何种方式排列,majority element 要么存在相邻,要么以majority element结尾,加上majority element的频数最高,这样一来,通过扫描一遍,扫出来的只会剩下majority element。(有点排列组合的味道)

O(n) time O(1) space fastest solution

public class Solution {
    public int majorityElement(int[] num) {

        int major=num[0], count = 1;
        for(int i=1; i<num.length;i++){
            if(count==0){
                count++;
                major=num[i];
            }else if(major==num[i]){
                count++;
            }else count--;

        }
        return major;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值