【java】力扣 合法分割的最小下标

题目链接

2780.合法分割的最小下标

题目描述

在这里插入图片描述

思路

这道题是摩尔算法的一种扩展
我们先可以找到候选人出来,然后去计算他在左右两边元素出现的次数,只有当他左边时,左边出现的次数2 >左边的长度,右边出现的次数2>右边的长度时 他才算做支配元素
先计算候选人在数组出现的总次数,然后再分别算左右出现的次数,然后算出
左边出现的次数2 >左边的长度,右边出现的次数2>右边的长度 此时的下标多少

代码

public int minimumIndex(List<Integer> nums) {
        int goal = findNum(nums);
        int count =0;
        for(int i=0;i<nums.size();i++){
            if(nums.get(i) ==goal)
                count++;
        }
        //左边众数出现的次数
        int countLeft =0;
        //右边众数出现的次数
        int countRight = count;

        //左边数组的元素个数
        int sizeLeft =1;
        //右边数组的元素个数
        int sizeRight = nums.size()-1;

        for(int i=0;i<nums.size();i++,sizeLeft++,sizeRight--){
            //记录当前元素
            int x =nums.get(i);
            if(x== goal){
                countLeft++;
                countRight--;
            }
            if(countLeft *2 >sizeLeft && countRight *2>sizeRight)
                return i;
        }
        return -1;
    }
    public int findNum(List<Integer> nums){
        int goal = 0;//候选人
        int count = 0;//候选人的票数
        for(int i=0;i<nums.size();i++){
            if(count == 0){
                goal = nums.get(i);
                count = 1;
            } else if(nums.get(i) ==goal){
                count++;
            }else{
                count--;
            }
        }
        return goal;
    }

感谢您的收看!!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值