48. 主元素 III
给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的
1/k
。
样例
例1:
输入: [3,1,2,3,2,3,3,4,4,4] and k=3,
输出: 3.
例2:
输入: [1,1,2] and k=3,
输出: 1.
挑战
要求时间复杂度为O(n),空间复杂度为O(k)
注意事项
数组中只有唯一的主元素
public class Solution {
/**
* @param nums: A list of integers
* @param k: An integer
* @return: The majority number
*/
public int majorityNumber(List<Integer> nums, int k) {
HashMap<Integer,Integer> hashMap=new HashMap<>();
int length=nums.size()/k;
for (int i = 0; i < nums.size(); i++) {
if (hashMap.containsKey(nums.get(i))){
int v=hashMap.get(nums.get(i));
v++;
if (length<v)return nums.get(i);
hashMap.put(nums.get(i),v);
}else {
hashMap.put(nums.get(i),1);
}
}
return 0;
}
}