剑指Offer面试题39. 数组中出现次数超过一半的数字

面试题39. 数组中出现次数超过一半的数字

题目

数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:

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

限制:

1 <= 数组长度 <= 50000

思路一

利用HashMap存储数组值及存在的次数。由于一个数组中有且仅有一个数字超过数组长度的一半,利用该特性不必遍历所有元素:
1、先判断该元素是否在哈希表中,存在,则将其数量+1;否认将其放入哈希表中,数量为1;
2、如果哈希表中该元素的数量已经大于数组长度的一半,则返回该值。

import java.util.HashMap;
public class MajorityElement {
    public int majorityElement(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        //根据题目可知,一个数组中有且仅有一个数字超过数组长度的一半
        int len = nums.length / 2;
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(nums[i])){
                map.put(nums[i], map.get(nums[i])+1);
            }else{
                map.put(nums[i], 1);
            }
            if(map.get(nums[i]) > len) return nums[i];
        }
        return 0;//默认不存在
    }
    
    public static void main(String[] args){
        MajorityElement test = new MajorityElement();
        int[] arr = {1,2,3,2,2,2,5,4,2};
        int result = test.majorityElement(arr);
        System.out.println(result);
    }
}

执行结果1

思路二

由于数字中一定存在一个数字出现的次数超过数组长度的一半,则将数组排序后,位于中间的数字一定是这个数字。

import java.util.Arrays;
public class MajorityElement {
    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }
    public static void main(String[] args){
        MajorityElement test = new MajorityElement();
        int[] arr = {1,2,3,2,2,2,5,4,2};
        int result = test.majorityElement(arr);
        System.out.println(result);
    }
}

执行结果2

思路三

假设第一次出现的数字是众数,与之后的数字比较,如果相等,计数count++如果不相等,count–;当count == 0时,说明target不是众数,则令target为当前数字(即默认当前数字为众数)。

class Solution {
    public int majorityElement(int[] nums) {
        int target = nums[0];
        if(nums.length == 1) return target;
        int count = 1;
        //一次遍历:重复次数最多的数字,其次数大于数组的一半,则在遍历过程中,遇到其他数字,其次数-1,则最后留下的一定是该数字
        for(int i = 1; i < nums.length; i++){
            if(target == nums[i]){
                count++;
            }else{
                count--;
            }
            if(count == 0){
                target = nums[i];
                count++;
            }
        }
        return target;
    }
}

执行结果3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值