• 求众数leetcode(169)+投票算法


    求众数

    解题思路:Boyer-Moore、KMP

    class Solution {
        public int majorityElement(int[] nums) {
            int len = nums.length;
            int conditate = 0;
            int count = 0;
            for(int i=0;i<len;++i){
                if(count == 0){
                    conditate = nums[i];
                }
                count +=(conditate==nums[i])?1:-1;
            }
            return conditate;
        }
    }

     求众数2:

    题目:给定一个大小为 的数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素

    解题思路:投票算法

    class Solution {
        public List<Integer> majorityElement(int[] nums) {
        List<Integer> res = new ArrayList<>();
        if (nums == null || nums.length == 0)
            return res;
        //初始化:定义两个候选人及其对应的票数
        int candidateA = nums[0];
        int candidateB = nums[0];
        int countA = 0;
        int countB = 0;
        //遍历数组
        for (int num : nums) {
            if (num == candidateA) {
                countA++;//投A
                continue;
            }
            if (num == candidateB) {
                countB++;//投B
                continue;
            }
    
            //此时当前值和AB都不等,检查是否有票数减为0的情况,如果为0,则更新候选人
            if (countA == 0) {
                candidateA = num;
                countA++;
                continue;
            }
            if (countB == 0) {
                candidateB = num;
                countB++;
                continue;
            }
            //若此时两个候选人的票数都不为0,且当前元素不投AB,那么A,B对应的票数都要--;
            countA--;
            countB--;
        }
    
        //上一轮遍历找出了两个候选人,但是这两个候选人是否均满足票数大于N/3仍然没法确定,需要重新遍历,确定票数
        countA = 0;
        countB = 0;
        for (int num : nums) {
            if (num == candidateA)
                countA++;
            else if (num == candidateB)
                countB++;
        }
        if (countA > nums.length / 3)
            res.add(candidateA);
        if (countB > nums.length / 3)
            res.add(candidateB);
        return res;
      }
    }

    投票算法图解:

  • 相关阅读:
    JS各种各样的拖动效果
    GridView实现自动编号
    通用海量数据库翻页
    设置首页和添加到收藏夹的JavaScript代码
    JavaScript弹出窗口总结
    JavaScript获取窗口的高度和宽度
    精妙SQL语句
    Javascript 操作select控件大全(新增、修改、删除、选中、清空、判断存在等)
    GridView数据导入Excel
    网站采集
  • 原文地址:https://www.cnblogs.com/erdanyang/p/11496335.html
Copyright © 2020-2023  润新知