LeetCode -- Majority Element寻找众数

197 阅读1分钟

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:双重遍历暴力法,时间复杂度O(N^2),空间复杂度O(1)。

public int majorityElement(int[] nums){
    int halfLength = nums.length / 2;
    for(int num : nums){
        int count = 0;
        for(int num2 : nums){
            if(num2 == num){
                count++;
            }
        }
        if(count > halfLength){
            return num;
        }
    }
    return -1;
}

解法2:使用HashMap遍历。时间复杂度O(N),空间复杂度O(N).

public int majorityElement(int[] nums) {
    Map<Integer,Integer> map = new HashMap();
    int length = nums.length;
    for(int i=0; i<length; i++){
        int key = nums[i];
        if(map.containsKey(key)){
            map.put(key,map.get(key)+1);
        }else{
            map.put(key,1);
        }
    }
    
    Map.Entry<Integer, Integer> majorityEntry = null;
    for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
        if (majorityEntry == null || entry.getValue() > majorityEntry.getValue()) {
            majorityEntry = entry;
        }
    }

    return majorityEntry.getKey();
}

解法3:先数组排序,然后找到下标为 nums.length/2的值即为众数。时间复杂度O(NlogN),空间复杂度为O(1)(如果不能修改原数组,则需要O(N)空间)。

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

解法4:Boyer-Moore Voting Algorithm 又称多数投票算法。时间复杂度O(N),空间复杂度O(1)。

原理:遍历数组nums,候选数字candidate从nums[0]开始,与candidate相等,则count+1,否则count-1。当count为0,candidate重新赋值当前下标数字。便利最后的候选人就是众数。最小的count值是众数与其他所有数的个数差。

public int majorityElement(int[] nums){
    int count = 0;
    int candidate = nums[0];
    for(int num : nums){
        if(count == 0){
            candidate = num;
        }
        count += (candidate == num)? 1: -1;
    }
    return candidate;
}