Given an array of integers and a number k, the majority number is the number that occurs more than 1/k
of the size of the array.
Find it.
Notice
There is only one majority number in the array.
Example
Given [3,1,2,3,2,3,3,4,4,4]
and k=3
, return 3
.
Challenge
O(n) time and O(k) extra space
public class Solution { /** * @param nums: A list of integers * @param k: As described * @return: The majority number */ public int majorityNumber(ArrayList<Integer> nums, int k) { // write your code if(nums == null || nums.size() == 0 || k < 1) return 0; if(k == 1) return nums.get(0); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int size = nums.size(); for(int i = 0; i < size; i++){ int temp = nums.get(i); if(map.containsKey(temp)){ map.put(temp, map.get(temp) + 1); } else{ if(map.size() < k){ map.put(temp, 1); } else{ Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<Integer, Integer> entry = it.next(); if(entry.getValue() == 1){ it.remove(); } else{ entry.setValue(entry.getValue() - 1); } } } } } int count = 0; int result = 0; for(Map.Entry<Integer, Integer> entry: map.entrySet()){ int candidate = entry.getKey(); int num = 0; for(int i = 0; i < size; i++) if(nums.get(i) == candidate) num++; if(num > count){ count = num; result = candidate; } } return result; } }