Loading

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

题目

给定数组里面有若干数字,找出其中出现次数超过一半的数。

思路1

使用hashmap统计,然后遍历hashMap这样就能轻易的求解

思路2

摩尔投票法:

推论一: 若记 众数 的票数为 +1+1 ,非众数 的票数为 -1−1 ,则一定有所有数字的 票数和 > 0>0 。

推论二: 若数组的前 aa 个数字的 票数和 = 0=0 ,则 数组剩余 (n-a)(n−a) 个数字的 票数和一定仍 >0>0 ,即后 (n-a)(n−a) 个数字的 众数仍为 xx 。

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/

代码

class Solution {
    public int majorityElement(int[] nums) {
        int num= 0, votes = 0;
        for (int i = 0;i < nums.length; i ++) {

            if(votes == 0) {
                num = nums[i];
            }
            votes += nums[i] == num ? -1 : 1;
        }
        int count = 0;
        for (int c: nums) {
            if (c == num) {
                count++;
            }
        } 
       
        return count > (nums.length >> 1) ? num : -1; 
    }
}
posted @ 2021-01-03 17:13  lijuny  阅读(106)  评论(0编辑  收藏  举报