Given an array of integers, the majority number is the number that occurs more than 1/3 of the size of the array.
Find it.
Have you met this question in a real interview? Yes
Example
Given [1, 2, 1, 2, 1, 3, 3], return 1.
Note
There is only one majority number in the array.
Challenge
O(n) time and O(1) extra space.
public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
// 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/3) {
return item;//遍历
}
}
return -1;
}
}