剑指offer39 数组中超过一半的数字

1. 题解

具体题解可以去看官网上https://leetcode.cn/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/
本节主要针对为什么要设第一个元素为众数,最后还能得出正确答案来解释.

在这里插入图片描述

2. 代码

 // 203. 数组中超过一半的元素
    public int majorityElement(int[] nums) {
        int x=0;// 设初始众数为0
        int votes=0; //初始总票数为0;
        for (int num : nums) {
            if (votes==0){
                x=num;
            }
            votes+=(x==num ? 1 : -1);
        }
        return x;
    }           

3. 法2

在这里插入图片描述

   // 法二 基于 Partion函数的解法
    // 203. 数组中超过一半的元素
    public int majorityElement(int[] nums) {
        int start=0;
        int end=nums.length-1;
        int mid=(end-start+1)/2;
        int index = partion(nums, start, end);
        while (index!=mid){//没找到中间下标的元素
            if (index<mid){// 排序后下标为mid的元素在右边
                start=index+1;
                index=partion(nums,start,end);
                continue;
            }

            if (index>mid){
                end=index-1;
                index=partion(nums,start,end);
                continue;
            }
            
            
        }
        return nums[index];
    }

    /**
     * 快排中的partion
     * @param arr
     * @param start
     * @param end
     * @return
     */
    public int partion(int[] arr,int start,int end){ //
        int index;
        if(end!=start){
             index=getRandomIndex(start,end);
        }else{
             index=start;
        }
       
        int temp=arr[index];// temp存储基准元素
        int t=arr[index];
        arr[index]=arr[start];
        arr[start]=t;  //将基准调到第一位;
        int small=start; // <= 基准的最大下标
        for (int i = start+1; i <=end ; i++) {
            if (arr[i]<temp){
                t=arr[++small];
                arr[small]=arr[i];
                arr[i]=t;
            }
        }
        //循环完成,此时small指向最后一个小于等于基准的元素,将第一个与small交换
        t=arr[small];
        arr[small]=arr[start];
        arr[start]=t;
        return small;
    }
    public int getRandomIndex(int start,int end){
        Random random = new Random();
        return random.nextInt(end-start)+start;
    }                                                             
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

弈师亦友

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值