题解 | #数组中出现次数超过一半的数字#

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

http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163

用的是摩尔投票法,这个题和 LeetCode 剑指offer 39题 有点类似,但是不同点在于这个题可能不存在众数,因此需要在最后还对之前统计的数字的个数进行一次判断,是否超过了一半的次数。

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        int vote = 0;
        int x = 0;
        for (int num : array) {
            // 如果之前的结果是正负投票已经抵消那就重新投当前的票,否则就对其进行判断是或和上次的一致不一致就-1,一致就+1
            if (vote == 0) {
                x = num;
                vote = 1;
            } else {
                vote += x == num ? 1 : -1;
            }
        }
        // 重新统计出现的次数是否超过了数组长度的一半
        int y = 0;
        for (int num : array) {
            if (num == x) {
                y++;
            }
        }
        return y > array.length / 2 ? x : 0;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务