Given an array of integers and a number k, the majority number is the number that occursmore than 1/k
of the size of the array.
Find it.
Example
Given [3,1,2,3,2,3,3,4,4,4]
and k=3
, return 3
.
Note
There is only one majority number in the array.
Challenge
O(n) time and O(k) extra space
对于1/k 的数,每当要删除的时候,要把k的数字同时删掉,这样不会影响最终的结果。
1 public class Solution { 2 /** 3 * @param nums: A list of integers 4 * @param k: As described 5 * @return: The majority number 6 */ 7 public int majorityNumber(ArrayList<Integer> nums, int k) { 8 // write your code 9 HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); 10 for(int i = 0; i < nums.size(); i ++){ 11 int num = nums.get(i); 12 if(map.containsKey(num)){ 13 map.put(num, map.get(num) + 1); 14 }else{ 15 if(map.size() < 3){ 16 map.put(num, 1); 17 }else{//decrease every count by one, remove pair which count is 0 18 ArrayList<Integer> removeKey = new ArrayList<Integer>(); 19 for (Map.Entry en : map.entrySet()){ 20 en.setValue((int)en.getValue() - 1); 21 if((int)en.getValue() == 0){ 22 removeKey.add((int)en.getKey()); 23 } 24 } 25 for(int j = 0; j < removeKey.size(); j ++){ 26 map.remove(removeKey.get(j)); 27 } 28 } 29 } 30 } 31 32 int result = 0; 33 int resultValue = 0; 34 for (Map.Entry cur : map.entrySet()){ 35 if((int)cur.getValue() > resultValue){ 36 result = (int)cur.getKey(); 37 resultValue = (int)cur.getValue(); 38 } 39 } 40 return result; 41 } 42 }