力扣 39 数组中出现次数超过一半的数字 摩尔投票

题目链接

代码

    /**
     * 摩尔投票
     * 用投票抵消的思路来解题,如果当前的数字和下一个数字相等,那么可以抵消的票数
     * +1,如果不相等,那么-1
     *
     */

    public int majorityElement(int[] nums) {
        int ans = 0, votes = 0;
        
        for (int x : nums) {
            if (votes == 0) ans = x;
            // 这样下来,第一个数字的票数一定是1,并且默认选中
            // 当票数为零,那么就要换一个数字接着尝试了
            votes += x == ans ? 1 : -1;
        }
    }

// 作者:jyd
// 链接:https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/mian-shi-ti-39-shu-zu-zhong-chu-xian-ci-shu-chao-3/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2020-10-23 08:31  Bears9  阅读(87)  评论(0编辑  收藏  举报