您的位置:首页 > 其它

集合框架的使用---Majority Number II

2016-01-27 14:06 344 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: