题目地址:
相似题目:
今天刷库存管理II(数组出现次数超过一半的数字),大家有兴趣可以点上看看题目要求,试着做一下。
我们直接看题解吧:
方法1,哈希表,key记录数组对应元素,value记录对应元素出现次数
方法2,先排序,然后取数组中点即为该众数
方法2,摩尔投票法
思路(摩尔投票法):
- 初始化,votes记录票数,众数x
- 循环数组:遍历数组每个元素num
·当票数votes=0时,假设当前数字num为众数
·当num==x时,votes++,当num==x时,votes--
3、返回x即可。
代码:
class Solution {
public int inventoryManagement(int[] stock) {
int x = 0, votes = 0;
for(int num : stock){
if(votes == 0) x = num;
votes += num == x ? 1 : -1;
}
return x;
}
}
代码(哈希表):
class Solution {
public int inventoryManagement(int[] stock) {
int n=stock.length;
HashMap<Integer,Integer>Hashtable=new HashMap<Integer,Integer>();
for(int i=0;i<n;i++){
if(Hashtable.containsKey(stock[i]))
Hashtable.put(stock[i],Hashtable.get(stock[i])+1);
else Hashtable.put(stock[i],1);
}
for(int i=0;i<n;i++){
if(Hashtable.get(stock[i])>n/2){
return stock[i];
}
}
return -1;
}
}
上一篇地址: