LeetCode算法题-Majority Element(Java实现)

算法MAJORITY(寻找多数元素) 寻找多数元素。用递归算法MAJORITY实现多数的寻找,其中调用candidate(m)函数。 立即下载

这是悦乐书的第181次更新,第183篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第40题(顺位题号是169)。给定大小为n的数组,找到数组中出现次数超过n/2的元素。假设该数组非空,并且该元素始终存在于数组中。例如:

输入:[3,2,3]
输出:3

输入:[2,2,1,1,1,2,2]
输出:2

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

我们可以先将数组排序,然后使用for循环遍历前n-1个元素,使用count计算元素出现的次数。

如果第i个元素与第i+1个元素相等,并且i等于数组长度减2,那么count要加两次,否则只用加1此,接着判断count是否大于n/2,如果大于则返回第i个元素。

如果第i个元素与第i+1个元素不相等,这时需要判断i是否大于0并且第i个元素与第i-1个元素是否相等,如果相等,count加1,接着判断count是否大于n/2,如果大于则返回第i个元素,如果不相等,count归为0,再重新开始循环。

因为题目已经表示数组不会为空,所以不需要考虑特殊情况,但是有一点就要考虑,那就是如果没有找到那个出现次数大于n/2的元素,需要返回数组最后一个元素。

public int majorityElement(int[] nums) {
    int size = nums.length / 2;
    int result = nums[nums.length - 1];
    Arrays.sort(nums);
    int count = 0;
    for (int i = 0; i < nums.length - 1; i++) {
        if (nums[i] == nums[i + 1]) {
            if (i == nums.length - 2) {
                count++;
            }
            count++;
            if (count > size) {
                return nums[i];
            }
        } else {
            if (i > 0 && nums[i] == nums[i - 1]) {
                count++;
                if (count > size) {
                    return nums[i];
                }
            } else {
                count = 0;
            }
        }
    }
    return result;
}

此解法的时间复杂度是O(n log(n))+O(n),空间复杂度是O(1)。

03 第二种解法

还是先利用Arrays的排序方法,将数组排序。题目要找的是出现次数大于n/2的元素,那么排过序后,假如存在该元素,那么数组的中间位元素,即nums[n/2]应该就是该元素。

但是,还需要一步判断,如果数组长度是偶数,比如是4,那么中间位元素是nums[2],即是数组第三位元素,这时就需要判断nums[1]和nums[0]是否相等了,如果相等那么返回nums[0]或者nums[n/2 - 1]都行。

public int majorityElement2(int[] nums) {
    int len = nums.length;
    if(len == 1) return nums[0];
    Arrays.sort(nums);
    if (len%2 == 0 && nums[0] == nums[len/2 - 1]) {
        return nums[0];
    }
    return nums[len/2];
}

此解法的时间复杂度是O(n log(n)),空间复杂度是O(1)。

04 第三种解法

取一临时变量candidate,存储出现次数大于n/2的元素。取一临时变量count,存储出现次数.

进入循环,判断count是否等于0,等于0,就将当前元素赋值给candidate。接着判断当前元素是否和candidate相等,相等的话count加1,否则减1,直到遍历完所有元素。

此解法,关键在于,碰到当前重复元素就加1,没碰到就减1,如果最后count不等于0,当前重复元素就是出现次数最多的元素,如果count变成0了,说明之前遇到的重复元素和不重复元素出现次数是相等的,相互抵消了,就需要重新去获取当前重复元素了。

public int majorityElement3(int[] nums) {
    int count = 0;
    int candidate = 0;
    for (int i = 0; i < nums.length; i++) {
        if (count == 0) {
            candidate = nums[i];
        }
        if (nums[i] == candidate) {
            count++;
        } else {
            count--;
        }
    }
    return candidate;
}

此解法的时间复杂度是O(n),空间复杂度是O(1)。

05 第四种解法

使用HashMap,key存储数组元素,value存储元素出现的次数,如果最后value值大于n/2,那么该key就是出现次数最多的元素。

public int majorityElement4(int[] nums) {
    Map<Integer, Integer> map = new HashMap<>();
    int freq = 0;
    for (int i = 0; i < nums.length; i++) {
        if (map.containsKey(nums[i])) {
            freq = map.get(nums[i]) + 1;
            map.put(nums[i], freq);
        } else {
            freq = 1;
            map.put(nums[i], 1);
        }
        if (freq > nums.length / 2)
            return nums[i];
    }
    return nums[nums.length-1];
}

此解法的时间复杂度是O(n),空间复杂度是O(n)。

06 测试与验证

针对以上四种解法,使用随机的数组和编写了简易的测试代码来测试这几种方法。如下:

public static void main(String[] args) {
    Easy_169_MajorityElement instance = new Easy_169_MajorityElement();
    int[] arg = { 3, 2, 3, 1, 2, 3, 2, 3};
    long start = System.nanoTime();
    int result = instance.majorityElement(arg);
    long end = System.nanoTime();
    System.out.println("majorityElement---输入:" + Arrays.toString(arg) + " , 输出:" + result + " , 用时:" + ((end - start) / 1000) + "微秒");
    int[] arg2 = { 3, 2, 3, 1, 2, 3, 2, 3};
    long start2 = System.nanoTime();
    int result2 = instance.majorityElement2(arg2);
    long end2 = System.nanoTime();
    System.out.println("majorityElement2---输入:" + Arrays.toString(arg2) + " , 输出:" + result2 + " , 用时:" + ((end2 - start2) / 1000) + "微秒");
    int[] arg3 = { 3, 2, 3, 1, 2, 3, 2, 3};
    long start3 = System.nanoTime();
    int result3 = instance.majorityElement3(arg3);
    long end3 = System.nanoTime();
    System.out.println("majorityElement3---输入:" + Arrays.toString(arg3) + " , 输出:" + result3 + " , 用时:" + ((end3 - start3) / 1000) + "微秒");
    int[] arg4 = { 3, 2, 3, 1, 2, 3, 2, 3};
    long start4 = System.nanoTime();
    int result4 = instance.majorityElement4(arg4);
    long end4 = System.nanoTime();
    System.out.println("majorityElement4---输入:" + Arrays.toString(arg4) + " , 输出:" + result4 + " , 用时:" + ((end4 - start4) / 1000) + "微秒");
}

测试结果如下:

majorityElement---输入:[1, 2, 2, 2, 3, 3, 3, 3] , 输出:3 , 用时:211微秒
majorityElement2---输入:[1, 2, 2, 2, 3, 3, 3, 3] , 输出:3 , 用时:5微秒
majorityElement3---输入:[3, 2, 3, 1, 2, 3, 2, 3] , 输出:2 , 用时:4微秒
majorityElement4---输入:[3, 2, 3, 1, 2, 3, 2, 3] , 输出:3 , 用时:62微秒

07 小结

算法专题目前已连续日更超过一个月,算法题文章40+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

桌面云架构讲解(VDI、IDV、VOI/TCI、RDS) 什么是云桌面桌面云是虚拟化技术成熟后发展起来的一种应用,桌面云通常也称为云桌面、VDI等桌面云中的云一般指的是企业的数据中心,通过在数据中心的服务器上安装若干个虚拟机,这个虚拟机就是桌面;但是终端无法直接连接到这个虚拟机(云桌面),因此就需要通过技术将就虚拟机变为桌面云发放出来;发放出来之后只需要瘦客户端(PC、手机、瘦客户机等)连接到数据中心的云桌面服务器平台,最终就可以连接到桌面来进行使用云桌面的优势终端与数据信息分离,数据在后台集中处理和存储 ,数据实现统一管理。 阅读详情

相关推荐

SAP采购含税价转换的底层逻辑解析:ABAP例程如何实现价税分离计算

本文深入解析SAP系统中采购含税价与不含税价的转换机制,重点介绍VOFM例程和ABAP代码实现价税分离计算的方法。通过详细讲解数学原理、税率体系及SAP定价引擎架构,为开发人员提供完整的解决方案,帮助提升采购业务中的价格处理效率和准确性。

weixin_29237635的博客 451

LeetCode 169. Majority Element 题解

题目描述: 169. Majority Element   Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the a

daqiang95的博客 450

从零构建企业级多智能体系统:LangGraph 全流程实战 + 部署指南(含代码与架构图)

> 在大模型应用爆发的今天,如何构建一个可协作、可调试、可部署的多智能体系统?LangGraph 正在成为工程师的新宠。本文从原理剖析、流程建模、代码实战到前后端部署,手把手带你用 LangGraph 构建一个企业级 AI 助理系统,整合财务分析、法务审阅、报告生成与图表可视化等 Agent 模块,全面打通从用户输入到报告输出的全链路闭环。适合有工程思维的 AI 架构师、Agent 研发人员、以及大模型项目实践者。

努力分享一些人工智能、计算机视觉、影像等相关的知识干货! 3451

(算法设计技巧与分析)Majority

#include using namespace std; int Condidate(int a[],int n,int j); int main() { int count=0; int a[12]={1,1,1,1,1,1,2,2,2,2,2,2}; int c=Condidate(a,12,0); for(int i=0;i<12;i++) if(a[i]==c) cou

lonely_Quan的专栏 1309

别再调PID了!用MATLAB/Simulink给四旋翼无人机搭个ADRC控制器(附完整仿真模型)

本文详细介绍了在MATLAB/Simulink环境中为四旋翼无人机搭建ADRC控制器的完整流程,包括核心原理、Simulink建模、参数调试技巧及与PID控制的性能对比。ADRC通过扩张状态观测器(ESO)有效提升无人机在复杂扰动下的控制性能,特别适合四旋翼无人机这类强耦合系统。文章还提供了完整的仿真模型和工程实践问题解决方案。

weixin_26808439的博客 383

从IPv6到Tomcat:彻底解决127.0.0.1拒绝连接的完整指南

本文提供了从IPv6到Tomcat的全面指南,帮助开发者彻底解决127.0.0.1拒绝连接的问题。涵盖网络协议栈、服务配置、端口管理等多个层面的排查方法,特别针对Tomcat服务提供了专项解决方案,确保开发者能够快速定位并修复连接问题。

weixin_29207439的博客 473

算法分析与设计第五次作业(leetcode 中 Majority Element 题解)

心得体会 这个题目有两个版本Majority Element,和Majority Element II,标记都表示hard,但是我自己觉得不简单,所以就写下来

ousuixin的博客 640

保姆级教程:手把手教你给联想System x 3650 M5服务器配置RAID 5并U盘装系统

本文提供联想System x 3650 M5服务器配置RAID 5并U盘安装系统的详细教程,特别适合零基础运维人员。从准备工作、RAID 5配置到U盘引导和系统安装,涵盖全流程关键步骤与常见问题解决方案,帮助用户高效完成服务器部署。

weixin_42535703的博客 360

LintCode majority numbe (主元素)

LintCode 主元素主元素 给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。给出数组[1,1,1,1,2,2,2],返回 1 挑战 要求时间复杂度为O(n),空间复杂度为O(1) 。solution: 对于这个问题,有很多解决的方法。Method1. 最基本的解决方法 使用两个for循环计算出每个元素出现的次数, 如果该次数大于数组元素的二分之一就返回

david_liang 1023

利用MobaXterm解密Session密码的实战指南

本文提供了利用MobaXterm解密Session密码的详细实战指南,帮助运维工程师和开发者在忘记密码时找回加密存储的远程连接信息。通过Python脚本和注册表操作,逐步解析MobaXterm的AES加密机制,实现密码解密,并分享安全建议和常见问题解决方案。

weixin_26759093的博客 232

基于航天宏图PIE-SAR软件的高分三号(GF-3)SAR影像的预处理

软件官网 航天宏图—国内领先的卫星运营与应用服务提供商(官网) 一、数据导入 数据导入-GF-3-根据模式选择 参数文件导入解压后GF-3数据的XML文件 通道自动填充 设置输出目录 确定 等待,加载图像、自动构建金字塔 二、复数数据转换 强度/幅度特征是SAR影像最主要的特征之一,基于SAR强度/幅度影像可以提取地物目标信息,因此需要将SAR复数数据转换为SAR强度/幅度数据。导入输入影像,设置参数类型,输出目录、命名、类型; 漫长的等待 三、多视 为提...

weixin_52127098的博客 9004

数据结构与算法应用(四):Majority Number II

No.1-2 Majority Number II Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array. Find it.Note There is only one majority number in the arr

风的专栏 1458

yolov26改进 | Neck/颈部创新篇 | 独创HFPN利用分层特征融合块HFFB模块融合多层次特征改进yolov26(全网独家创新)

本文提出了一种创新的分层特征融合模块HFFB(Hierarchical Feature Fusion Block)来改进YOLOv26的neck部分,构建了名为HFPN的新型特征金字塔网络。该模块通过三分支结构融合局部特征(CNN提取)、全局特征(Swin Transformer提取)和中间特征,并包含空间注意力(SA)、通道注意力(CA)和残差反向MLP(IRMLP)等组件来优化特征融合效果。实验表明,该方法能针对不同尺度目标(大/中/小)进行自适应检测,可根据具体数据集需求选择不同配置。文章详细提供了核

Snu77的博客 486

格雷通路 算法 java,LeetCode算法题-Majority Element(Java实现)

这是悦乐书的第181次更新,第183篇原创 01 看题和准备今天介绍的是LeetCode算法题中Easy级别的第40题(顺位题号是169)。给定大小为n的数组,找到数组中出现次数超过n/2的元素。假设该数组非空,并且该元素始终存在于数组中。例如:输入:[3,2,3] 输出:3输入:[2,2,1,1,1,2,2] 输出:2本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win...

weixin_34812649的博客 162

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

LeetCode 169. Majority Element

欢迎访问原文所在博客:https://52heartz.top/articles/leetcode-169-majority-element/ 解答1[Java]: class Solution { public int majorityElement(int[] nums) { int count = 0; Integer candidate = null...

user2639的博客 166

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

leetcode 169. Majority Element

leetcode 169. Majority Element题目 Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is n

Decorator2015的博客 700

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

【LeetCode】 169. Majority Element 多数元素(Easy)(JAVA)每日一题

【LeetCode】 169. Majority Element 多数元素(Easy)(JAVA) 题目地址: https://leetcode.com/problems/majority-element/ 题目描述: Given an array of size n, find the majority element. The majority element is the element t...

qq_16927853的博客 185

leetcode-169. Majority Element

leetcode-169. Majority Element Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-e

link98 340

【LeetCode】169. Majority Element 多数元素(Easy)(JAVA)

【LeetCode】169. Majority Element 多数元素(Easy)(JAVA) 题目地址: https://leetcode.com/problems/majority-element/ 题目描述: Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that

qq_16927853的博客 171

Leetcode之分治法专题-169. 求众数(Majority Element)

Leetcode之分治法专题-169. 求众数(Majority Element) 给定一个大小为n的数组,找到其中的众数。众数是指在数组中出现次数大于⌊ n/2 ⌋的元素。 你可以假设数组是非空的,并且给定的数组总是存在众数。 示例1: 输入: [3,2,3] 输出: 3 示例2: 输入: [2,2,1,1,1,2,2] 输出: 2 分治法,...

denghan1065的博客 653

LeetCode 169 --- Majority Element

题目链接: LeetCode 169 — Majority Element AC代码:public class Problem169 { public int majorityElement(int[] nums) { int m=nums[0],n=0; for(int i=0;i<nums.length;i++){ if(num

调包侠 255

LeetCode 229 --- Majority Element II

题目链接: LeetCode 229 — Majority Element IIAC代码:public class Problem229 { public static void main(String[] args) { // TODO Auto-generated method stub int[] name ={1,1,1,2,3}; m

调包侠 407

C 语言构造hash table 解 LC majority element问题

Leetcode上 majority element这题是 有 时间O(N), 空间O(1)的解的. https://leetcode.com/problems/majority-element/ 用hash table来解则为时间O(N), 空间O(N). 如果是Java里 用HashMap很方便了. 有位同学问怎么用c语言来构造hash table. 我就随手写了一个: ...

132

leetcode169 Majority Element

package array; import java.util.HashMap; public class leetcode169MajorityElement { /* Given an array of size n, find the majority element. The majority element is the element that appear...

离镜的博客 360

Leetcode 229. Majority Element II

Leetcode 229. Majority Element II Given an integer array of size n, find all elements that appear more than ⌊n/3⌋⌊n/3⌋\lfloor n/3 \rfloor times. The algorithm should run in linear time and in O(1)...

TooSchoolForCool 375
上一篇: LeetCode算法题-Excel Sheet Column Title(Java实现)
下一篇: LeetCode算法题-Excel Sheet Column Number(Java实现)
程序员小川
博客等级 码龄10年 47粉丝 305原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值