169、求众数
解法一:因为题目中说一定存在众数,且众数是出现次数超过长度的一半。所以本题可以先进行排序后,去数组最中间的那个数,因为众数超过一半,排序过后最中间的数肯定是众数。
class Solution { public int majorityElement(int[] nums) { int n = nums.length; Arrays.sort(nums); return nums[nums.length/2]; } }
解法二:hashmap的使用,遍历nums,判断nums[i]是否在hashmap中,存在则对应的value+1,不存在就重新put进去,并且设置value为1.最终遍历hashmap,找出value最大的对应的key即为所求众数。class Solution { public int majorityElement(int[] nums) { HashMap<Integer, Integer> hashMap = new HashMap<>(); for(int i = 0;i<nums.length;i++){ if(hashMap.containsKey(nums[i])){ hashMap.put(nums[i],hashMap.get(nums[i])+1); }else { hashMap.put(nums[i],1); } } for (Integer key:hashMap.keySet()){ if(hashMap.get(key) > nums.length/2 ) return key; } return 0; } }
解法三:分治法
LeetCode刷题笔记(Java版)----169、求众数
最新推荐文章于 2022-07-11 08:50:08 发布