LeetCode15_求众数(哈希表、排序、随机化、分治、Boyer-Moore 投票算法)

题目描述


多数元素

给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

  • 示例 1:
    输入:[3,2,3]
    输出:3
  • 示例 2:
    输入:[2,2,1,1,1,2,2]
    输出:2

一、我的解答

拒绝O(n^2)从你我做起~

排序,前后指针,计数判断

class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        int len = nums.length;
        if(len == 1){
    
    
            return nums[0];
        }
        Arrays.sort(nums);
        int first,second;
        int count = 1;
        for(int i = 0;i<len - 1;i++){
    
    
            first = nums[i];
            second = nums[i+1];
            if(first == second){
    
    
                count++;
                if(count > (len/2)){
    
    
                    return first;
                }
            }
            else{
    
    
                count = 1;

            }
        }
        return 0;

    }
}

二、题解

2.1哈希表

先建表,元素作为键,出现的次数作为值,后 遍历每个entry,找出最大的value对应的key

class Solution {
    
    
    private Map<Integer,Integer> countNums(int[] nums){
    
    
        Map<Integer,Integer> counts = new HashMap<Integer,Integer>();
        for(int num : nums){
    
    
            if(!counts.containsKey(num)){
    
    
                counts.put(num,1);
            }
            else{
    
    
                counts.put(num,counts.get(num) + 1);
            }
        }
        return counts;
    }
    public int majorityElement(int[] nums) {
    
    
        Map<Integer,Integer> counts = countNums(nums);

        Map.Entry<Integer,Integer> majorityEntry = null;
        //遍历每个entry,找出最大的value对应的key
        for(Map.Entry<Integer,Integer> entry : counts.entrySet()){
    
    
            if(majorityEntry == null || entry.getValue() > majorityEntry.getValue()){
    
    
                majorityEntry = entry;
            }
        }
        return majorityEntry.getKey();

    }
}

2.2排序

感觉这个很巧妙

如果将数组 nums 中的所有元素按照单调递增或单调递减的顺序排序,那么下标为 n/2 向下取整

的元素(下标从 0 开始)一定是众数。

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

2.3随机化

因为超过2/n ⌋ 的数组下标被众数占据了,这样我们随机挑选一个下标对应的元素并验证,有很大的概率能找到众数。

算法

由于一个给定的下标对应的数字很有可能是众数,我们随机挑选一个下标,检查它是否是众数,如果是就返回,否则继续随机挑选。

class Solution {
    
    
    private int randRange(Random rand, int min, int max) {
    
    
        return rand.nextInt(max - min) + min;
    }

    private int countOccurences(int[] nums, int num) {
    
    
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
    
    
            if (nums[i] == num) {
    
    
                count++;
            }
        }
        return count;
    }

    public int majorityElement(int[] nums) {
    
    
        Random rand = new Random();

        int majorityCount = nums.length / 2;

        while (true) {
    
    
            int candidate = nums[randRange(rand, 0, nums.length)];
            if (countOccurences(nums, candidate) > majorityCount) {
    
    
                return candidate;
            }
        }
    }
}

2.4分治

题解:LeetCode169-多数元素-easy

class Solution {
    
    
    private int countInRange(int[] nums, int num, int lo, int hi) {
    
    
        int count = 0;
        for (int i = lo; i <= hi; i++) {
    
    
            if (nums[i] == num) {
    
    
                count++;
            }
        }
        return count;
    }

    private int majorityElementRec(int[] nums, int lo, int hi) {
    
    
        // base case; the only element in an array of size 1 is the majority
        // element.
        if (lo == hi) {
    
    
            return nums[lo];
        }

        // recurse on left and right halves of this slice.
        int mid = (hi - lo) / 2 + lo;
        int left = majorityElementRec(nums, lo, mid);
        int right = majorityElementRec(nums, mid + 1, hi);

        // if the two halves agree on the majority element, return it.
        if (left == right) {
    
    
            return left;
        }

        // otherwise, count each element and return the "winner".
        int leftCount = countInRange(nums, left, lo, hi);
        int rightCount = countInRange(nums, right, lo, hi);

        return leftCount > rightCount ? left : right;
    }

    public int majorityElement(int[] nums) {
    
    
        return majorityElementRec(nums, 0, nums.length - 1);
    }
}

2.5投票算法
class Solution {
    
    
    public int majorityElement(int[] nums) {
    
    
        int count = 0;
        Integer candidate = null;

        for (int num : nums) {
    
    
            if (count == 0) {
    
    
                candidate = num;
            }
            count += (num == candidate) ? 1 : -1;
        }

        return candidate;
    }
}


猜你喜欢

转载自blog.csdn.net/qq_24654501/article/details/112158375