JZ28.数组中出现次数超过一半的数

法1:哈希表

遍历数组,数组元素作为key,出现次数作为值,存入哈希表

遍历哈希表,若某个值大于n/2,返回其key

import java.util.HashMap;
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        //哈希表
        HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
        int n = array.length;
        for(int i=0;i<n;i++){
            if(!hash.containsKey(array[i])){
                hash.put(array[i],1);
            }else{
                hash.put(array[i],hash.get(array[i])+1);
            }
        }
        for(int key:hash.keySet()){
            if(hash.get(key)>n/2)
                return key;
        }
        return 0;
    }
}

法2:投票法

具体做法:

  1. 初始化:候选人cond = -1, 候选人的投票次数cnt = 0
  2. 遍历数组,如果cnt=0, 表示没有候选人,则选取当前数为候选人,++cnt
  3. 否则,如果cnt > 0, 表示有候选人,如果当前数=cond,则++cnt,否则--cnt
  4. 直到数组遍历完毕,最后检查cond是否为众数
public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        //投票法
        //候选candidate为-1,候选数量count=0;
        //遍历数组,若无候选,则当前为候选,候选数量count++
        //若有,若当前和候选相同,则count++,否则count--
        //最后验证候选是否为众数
        int n =array.length;
        int candidate = -1;
        int count = 0;
        for(int i=0;i<n;i++){
            if(count==0){
                candidate = array[i];
                count++;
            }else{
                if(candidate==array[i])
                    count++;
                else
                    count--;
            }
        }
        count=0;
        for(int e:array){
            if(e==candidate)
                count++;
        }
        if(count>n/2)
            return candidate;
        else
            return 0;
    }
}

法3:排序法

排序,则可能的众数必然在数组中间,验证一下是不是。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值