首页 > 编程语言 >leetcode Boyer-Moore 算法

leetcode Boyer-Moore 算法

时间:2022-11-04 23:12:55浏览次数:64  
标签:count Moore candidate nums int 算法 leetcode Boyer

简介

如何寻求一个数组中的出现次数最多的书
虽然最开始想到了这个方法但是不知道如何去表达,grep就利用了这个算法

class Solution {
    public int majorityElement(int[] nums) {
        Integer candidate = null;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            if(candidate == null || count == 0) {
                candidate = nums[i];
            }
            if(candidate == nums[i]){
                count ++;
            }else{
                count --;
            }
        }
        return candidate;
    }
}

参考链接

https://leetcode.cn/problems/majority-element/solution/duo-shu-yuan-su-by-leetcode-solution/

标签:count,Moore,candidate,nums,int,算法,leetcode,Boyer
From: https://www.cnblogs.com/eat-too-much/p/16859395.html

相关文章

  • Leetcode刷题第二周
    链表:插入快,查询慢,存储不连续分为单链表,双链表和循环链表在链表中使用虚拟头结点,可以减少增删改查中对头结点的特殊处理移除链表元素203/***Definitionforsingly......
  • LeetCode 145. 二叉树的后序遍历
    问题描述给定一个二叉树,返回它的后序遍历。示例:进阶:递归算法很简单,你可以通过迭代算法完成吗?题目代码/***Definitionforabinarytreenode.*publicclassTre......
  • leetcode-2283-easy
    CheckifNumberHasEqualDigitCountandDigitValueYouaregivena0-indexedstringnumoflengthnconsistingofdigits.Returntrueifforeveryindexi......
  • leetcode-754-medium
    ReachaNumberYouarestandingatposition0onaninfinitenumberline.Thereisadestinationatpositiontarget.YoucanmakesomenumberofmovesnumMove......
  • leetcode-657-easy
    RobotReturntoOriginThereisarobotstartingattheposition(0,0),theorigin,ona2Dplane.Givenasequenceofitsmoves,judgeifthisrobotendsup......
  • leetcode-1417-easy
    ReformatTheStringYouaregivenanalphanumericstrings.(AlphanumericstringisastringconsistingoflowercaseEnglishlettersanddigits).Youhaveto......
  • leetcode-771-easy
    JewelsandStonesYou'regivenstringsjewelsrepresentingthetypesofstonesthatarejewels,andstonesrepresentingthestonesyouhave.Eachcharacterin......
  • leetcode-1200-easy
    MinimumAbsoluteDifferenceGivenanarrayofdistinctintegersarr,findallpairsofelementswiththeminimumabsolutedifferenceofanytwoelements.Retu......
  • leetcode-1984-easy
    MinimumDifferenceBetweenHighestandLowestofKScoresYouaregivena0-indexedintegerarraynums,wherenums[i]representsthescoreoftheithstudent.......
  • leetcode 160. 相交链表 js 实现
    给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。图示两个链表在节点 c1 开始相交: ......