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.
Have you met this question in a real interview? Yes
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
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
int n = nums.size();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int elem : nums) {
if (map.containsKey(elem)) {
map.put(elem, map.get(elem)+1);
}//添加元素.........取值
else {
map.put(elem, 1);//添加元素
}
}
for (int item : map.keySet()) {
if (map.get(item) > n/k) {
return item;//遍历
}
}
return -1;
}
}