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.
public class Solution { //更好的方法是排序,return 中间那个数 public int majorityElement(int[] nums) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i])) { map.put(nums[i], map.get(nums[i])+1); } else map.put(nums[i], 1); } Set set = map.entrySet(); Iterator it = set.iterator(); int res = 0; while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); if ((int) entry.getValue() > nums.length / 2) res = (int) entry.getKey(); } return res; } }