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.

首先想到的办法是设置两个变量,一个来定义major,另一个来记录循环到该位置时候,major和不是major的差值,如果差值为0了,就设定下一个数为major,代码如下:

public class Solution {

    public int majorityElement(int[] nums) {

        int major = nums[0];

        int count = 1;

        for(int i=1;i<nums.length;i++){

            if(count==0) major = nums[i];

            if(major==nums[i]) count++;

            else count--;

        }

        return major;

    }

}

接下来的一种做法是用hashmap的value值来存储key值出现的次数,如果value值大于nums.length/2,则key值就是major,(moor voting algorithm)代码如下:

public class Solution {

    public int majorityElement(int[] nums) {

        Map<Integer,Integer> map = new HashMap<Integer,Integer>();

        int major = Integer.MAX_VALUE;

        for(int i=0;i<nums.length;i++){

            map.put(nums[i],map.getOrDefault(nums[i],0)+1);

            if(map.get(nums[i])>nums.length/2) major= nums[i];

        }

        return major;

    }

}

结下来可以用排序做,然后取中间的额数就是major的数:

public class Solution {

    public int majorityElement(int[] nums) {

        Arrays.sort(nums);

        return nums[nums.length/2];

    }

}

用位操作也可以做出来,思路是major有32位,从右向左每一位依次设为1,其他位设为0,然后然后在该循环位的位置上将num循环一次,检验该位置为1的出现次数是否多余一半,如果多于一半,那么major上该位一定是1.(该方法正确性可以用反证法证明)代码如下:

public class Solution {

    public int majorityElement(int[] nums) {

        int major = 0;

        for(int i=0,mask = 1;i<32;i++,mask<<=1){

            int bitcount = 0;

            for(int j=0;j<nums.length;j++){

                if((nums[j]&mask)==mask) bitcount++;

                if(bitcount>nums.length/2){

                    major|=mask;

                }

            }

        }

        return major;

    }

}

原文地址:https://www.cnblogs.com/codeskiller/p/6354113.html