当前位置: 首页 > 后端技术 > Java

LeetCode-169-MostElements

时间:2023-04-01 15:05:57 Java

MostElements题目描述:给定一个大小为n的数组,找出其中的多数元素。众数元素是数组中出现次数超过?n/2?的元素。您可以假设数组是非空的,并且给定数组中的元素总是占多数。例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode网络所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:HashMap使用java的HashMap,key存储不同的数字,value存储对应数字出现的次数:遍历nums,将每个数字放入HashMap中;比较得到的HashMap,比较每个数出现的次数,得到出现次数最多的数,返回结果。解决方案2:摩尔投票算法摩尔投票算法是消耗两个不同的数字。由于总是存在多数元素,这意味着不同的数字被消耗后只能剩下多数元素。具体过程如下。用result记录最后的多数,初始化为数组的第一个元素,count记录这个数重复的次数:首先,如果count为0,说明之前的不同数已经被消耗完,resultassignedas对于当前数,计数为1;如果计数大于0:如果结果等于当前元素,则计数加1;如果结果不等于当前元素,则计数减一,即消耗一对不同的数。最后的结果一定是多数元素。importjava.util.HashMap;importjava.util.Map;publicclassLeetCode_169{/***方法一:HashMap**@paramnums*@return*/publicstaticintmajorityElement(int[]nums){Mapcount=newHashMap<>();for(intnum:nums){if(count.get(Integer.valueOf(num))==null){count.put(Integer.valueOf(num),1);}else{count.put(Integer.valueOf(num),count.get(Integer.valueOf(num))+1);}}int结果=-1,maxCount=-1;对于(Map.EntryintegerIntegerEntry:count.entrySet()){if(integerIntegerEntry.getValue()>maxCount){maxCount=integerIntegerEntry.getValue();结果=integerIntegerEntry.getKey();}}返回结果;}/***方法二:摩尔投票算法**@paramnums*@return*/publicstaticintmajorityElement2(int[]nums){int结果=nums[0],count=1;对于(inti=1;i