leetcode 169-Majority Element(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.

 

1. bit manipulation

count the ones and zeros on each bit of all numbers in nums, for those ones larger than zeros, put 1, otherwise, put 0;

class Solution {
    public int majorityElement(int[] nums) {
        int major=0;
        for(int i=0;i<32;i++){
            int zeros=0;
            int ones=0;
            for(int num:nums){
                if((num&(1<<i))!=0) ones++;
                else zeros++;
            }
            if(ones>zeros){
                major|=(1<<i);
            }
        }
        return major;
    }
}

这种方法肯定不是对于这道题的好方法,但对于bit manipulation太不熟悉,对这种方法从来没怎么用过,所以这里主要强调这种方法。

注意:

  (num&(1<<i))!=0,这里的括号不能掉,比特运算时运算符的优先级会存在一些问题,如果记不清楚以防万一就拿括号括起来保险!

 

2. moore voting

class Solution {
    public int majorityElement(int[] nums) {
        int num=0;
        int count=0;
        for(int n:nums){
            if(n==num) count++;
            else if(count==0){
                num=n;count=1;
            } 
            else count--;
        }
        return num;
    }
}

 

3. sort array 然后返回中间一个数

class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}

4. hashmap

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int num:nums){
            if(map.containsKey(num)) map.put(num,map.get(num)+1);
            else map.put(num,1);
            if(map.get(num)>nums.length/2) return num;
        }
        return 0;
        
    }
}

这种方法太慢了,不要用。

  

转载于:https://www.cnblogs.com/yshi12/p/9694487.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值