面试题 17.10 主要元素

​​题目来源:

leetcode题目,网址:面试题 17.10. 主要元素 - 力扣(LeetCode)

解题思路:

首先,顺序遍历数组,将不同的数字消去,最后留下的数字若计数小于等于 0,则不存在主要元素。然后遍历数组,对最后留下的数字计数,判断其是否是主要元素。

解题代码:

复制代码
class Solution {
    public int majorityElement(int[] nums) {
        int res=0;
        int cnt=0;
        for(int num:nums){
            if(num==res){
                cnt++;
            }else{
                cnt--;
                if(cnt<0){
                    res=num;
                    cnt=1;
                }
            }
        }
        if(cnt<=0){
            return -1;
        }
        
        int count=0;
        for(int num:nums){
            if(num==res){
                count++;
            }
        }
        return count>nums.length/2?res:-1;
    }
}
复制代码

总结:

官方题解也是一样的思路。通过 Boyer-Moore 投票算法得到可能的主要元素或表名不存在主要元素,然后判断可能的主要元素是否是主要元素。


相关推荐
资深web全栈开发16 小时前
LeetCode 3623. 统计梯形的数目 I
算法·leetcode·职场和发展·组合数学
h***047719 小时前
SpringBoot(7)-Swagger
java·spring boot·后端
v***913020 小时前
Spring boot创建时常用的依赖
java·spring boot·后端
代码or搬砖1 天前
MyBatisPlus讲解(二)
java·mybatis
lcu1111 天前
Java 学习42:抽象
java
Mr.朱鹏1 天前
RocketMQ安装与部署指南
java·数据库·spring·oracle·maven·rocketmq·seata
雨中飘荡的记忆1 天前
Spring表达式详解:SpEL从入门到实战
java·spring
Coder-coco1 天前
个人健康管理|基于springboot+vue+个人健康管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·mysql·论文
5***26221 天前
Spring Boot问题总结
java·spring boot·后端
xkroy1 天前
Spring Boot日志
java·spring boot·后端