力扣---剑指 Offer 39. 数组中出现次数超过一半的数字

发布时间 2023-04-12 21:07:31作者: Owlwu

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

你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
 
限制:
1 <= 数组长度 <= 50000

注意:本题与主站 169 题相同:https://leetcode-cn.com/problems/majority-element/


来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


 

三种思路。

1. 由于题目保证有答案,所以将数组排序后,处于中间的必定是答案。

2. 使用哈希表进行计数,当某个数出现的次数大于数组长度的一半后,直接返回该数即可。

3. 可以将所有不相同的数两两进行抵消,最后剩下的必定是答案。(参考随机一换一,人数多的必定留到最后)

前两种方法太简单,不写了,这里直接给第三种。

class Solution {
    public int majorityElement(int[] nums) {
        int res = nums[0];
        int count = 0;
        for (int i = 0; i < nums.length; i ++) {
            if (res == nums[i]) {
                count ++;
            } else {
                count --;
                if (count == 0) {
                    // 由于题目保证答案存在,所以这里不需要考虑越界问题。
                    res = nums[i + 1];
                }
            }
        }
        return res;
    }
}