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

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

  

posted on 2018-09-24 01:10  elsie12  阅读(73)  评论(0编辑  收藏  举报