Algorithm: Moore Voting Method

Problem Description:

Encountered an algorithm problem, find the number that appears most frequently in the array, and determine whether it exceeds half of the array.

solution

I first thought of 3 schemes. The
first one: use hashSet to pass in data, record the number of false, and finally compare with the array length.
The second type: use two pointers to compare whether the data is duplicated, if some, count+1, and compare with the length of the array.
The third type: The third type is an algorithm to be introduced in this article, Moore voting method. The first two can achieve functions, but there is a problem, both in complexity and space.

Moore voting

public static void main(String[] args) {
    
    
        /**
         * 如果数组中多一半的数都是同一个,则称之为主要元素。给定一个整数数组,找到它的主要元素。若没有,返回-1。
         *
         * 示例 1:
         * 输入:[1,2,5,9,5,9,5,5,5]
         * 输出:5
         *  
         * 示例 2:
         * 输入:[3,2]
         * 输出:-1
         *
         * 示例 3:
         * 输入:[2,2,1,1,1,2,2]
         * 输出:2
         *
         */

        int[] nums = {
    
    1,2,5,9,5,9,5,5,5};

        int i = 0;
        int count1 = 0;
        //遍历整个数组,在遍历的过程中找到出现次数最多的数
        for (int num : nums) {
    
    
            if (count1 == 0) {
    
    
                i = num;
                count1++;
            } else {
    
    
                if (i == num) {
    
    
                    count1++;
                } else {
    
    
                    count1--;
                }
            }
        }
        int count2 = 0;
        //先判断是否有众数
        if (count1 <= 0) {
    
    
            System.out.println(i);
        } else {
    
    
            //确认有众数之后就遍历数组  确定众数出现的次数
            for (int num : nums) {
    
    
                if (num == i) {
    
    
                    count2 ++;
                }
            }
        }
        //判断出现的次数是否超过数组的一半
        if (count2 > nums.length / 2) {
    
    
            System.out.println(i);
        }
    }

to sum up

This algorithm can not only find the number of occurrences more than half the length of the array, but also find one-third and so on.

Guess you like

Origin blog.csdn.net/weixin_46687295/article/details/106172051