给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.
样例
给出数组[1,1,1,1,2,2,2],返回 1
public class Solution {
/**
* @param nums: a list of integers
* @return: find a majority number
*/
public int majorityNumber(ArrayList<Integer> nums) {
// write your code
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
map.put(nums.get(0), 1);
for(int i=1;i<nums.size();i++){
if(map.containsKey(nums.get(i))){
map.put(nums.get(i), map.get(nums.get(i))+1);
}else{
map.put(nums.get(i), 1);
}
}
Set<Integer> set=map.keySet();
Iterator<Integer> it=set.iterator();
while(it.hasNext()){
int temp=it.next();
if(map.get(temp)>nums.size()/2){
return temp;
}
}
return 0;
}
}