[剑指 offer]--哈希表/摩尔投票--面试题39. 数组中出现次数超过一半的数字

1 题目描述

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

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

示例 1:

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

限制:

1 <= 数组长度 <= 50000

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

2 解题思路

  • 方法一: 排序后中间的那个数

哈哈哈哈哈哈需要的数字出现次数多于一半 那么排序后必定在中间

  • 方法二:哈希表统计法
    遍历数组 nums ,统计各数字的数量,最终超过数组长度一半的数字则为众数。
    此方法时间和空间复杂度均为O(N) 。
  • 方法三:摩尔投票法
    在这里插入图片描述

(1)变量初始化:res记录上次访问的元素,初始值为第一个元素
count进行计数,初始值为1
(2)如果下一个值]ums[i0和当前值res相同那么count++;
如果不同count–,
(3)减到0的时候就要更换新的res值了
此时res为最后访问的那个元素,即nums[i],count为1
(4) 返回值为最后一次访问的元素res
count的自加和自减就是在描述一种抵消关系,
由于超过一半的出现次数,导致最后的target一定会是该值

3 解决代码

  • 方法一: 排序后中间的那个数《Java代码》
class Solution {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
}
  • 方法二:哈希表统计法《Java代码》
class Solution {
    public int majorityElement(int[] nums) {
        for(int num:nums){
            int count = 0;
            for(int elem: nums){
                if(elem == num){
                    count += 1;
                }
            }
            if(count > nums.length / 2){
                return num;
            }
        }
        return -1;

    }
}
  • 方法三:摩尔投票法《java代码》
class Solution {
    public int majorityElement(int[] nums) {
        //初始化为数组的第一个元素,接下来用于记录上一次访问的值
        int res = nums[0];
        //用于记录出现次数
        int count = 1;
        for(int i = 1; i < nums.length; i++){
            if(res == nums[i]){
                count++;
            }else{
                count--;
            }
            //当count=0时,更换res的值为当前访问的数组元素的值,次数设为1
            if(count == 0){
            res = nums[i];
            count = 1;
            }
        }
        
        return res;

    }
}
  • 方法三:摩尔投票法《Python3代码》
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        res = nums[0]
        count = 1
        for i in range(1,len(nums)):
            if res == nums[i]:
                count = count + 1
            else:
                count = count - 1
            if count == 0:
                res = nums[i]
                count = 1
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值