LeetCode 169. Majority Element Java
题目:
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-empty and the majority element always exist in the array.
题意:给出一个长度为n的数组,查找其中的主要元素。主要元素即在数组中出现次数大于n/2的元素。题目假设数组不为空而且主要元素一定存在。最简单的方法就是使用一个hashMap存储元素出现的次数,然后遍历hashMap找出value大于n/2的key。
代码(使用hashMap的方法):
public class Solution { public int majorityElement(int[] nums) { HashMap<Integer, Integer> res=new HashMap<>(); for(int i=0;i<nums.length;i++){ if(res.containsKey(nums[i])){ int val=res.get(nums[i]); res.remove(nums[i]); res.put(nums[i], val+1); }else{ res.put(nums[i], 1); }; } Iterator iter = res.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); if((int)val>nums.length/2){ System.out.println(key); return (int)key; } } return 0; } }