文章482
标签257
分类63

算法:数组中出现次数超过一半的数字


数组中出现次数超过一半的数字

数组中出现次数超过一半的数字

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。

例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。

如果不存在则输出0。


分析

使用摩尔投票法[求众数]

在遍历数组时保存两个值:一是数组中一个数字,一是次数。

遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。

遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。


代码

public class Solution {
    public int MoreThanHalfNum_Solution(int[] array) {
        if (array == null || array.length == 0) throw new RuntimeException("Invalid parameter");
        if (array.length == 1) return array[0];

        int curNum = array[0], count = 1, len = array.length;
        for (int i = 1; i < len; ++i) {
            if (array[i] == curNum) {
                count++;
            } else {
                count--;
                if (count == 0) {
                    curNum = array[i];
                    count++;
                }
            }
        }

        int bound = len / 2;
        int cnt = 0;
        for (int n : array) {
            if (n == curNum) cnt++;
        }
        return cnt > bound ? curNum : 0;
    }
}

本文作者:Jasonkay
本文链接:https://jasonkayzk.github.io/1996/07/27/算法-数组中出现次数超过一半的数字/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可