1914. 聪明的销售
描述
销售主管的任务是出售一系列的物品,其中每个物品都有一个编号。
由于出售具有相同编号的商品会更容易,所以销售主管决定删除一些物品。
现在她知道她最多能删除多少物品,她想知道最终袋子里最少可以包含多少种不同编号的物品。
例如,最开始她有n = 6 个物品,编号为:ids = [1,1,1,2,2,3],她最多可以删除 m = 2 个物品。
如果删除两个物品 1,则剩下的物品 ids = [1,2,2,3],此时她拥有三种不同编号的物品。
如果删除两个物品 2,则剩下的物品 ids = [1,1,1,3],此时她拥有两种不同编号的物品。
如果删除物品 2 和物品 3 各 1个,则剩下的物品 ids = [1,1,1,2],此时她拥有两种不同编号的物品。
我们发现,物品最多可以剩下两种不同的编号,所以你的程序要返回 2
- ids 的大小不超过 105
- 1 <= ids[i] <= 1000000
- 1 <= m <= 100000
样例 1:
输入:
[1,1,1,2,2,3]
2
输出:
2
题解
public class Solution {
/**
* @param ids: ID number of items
* @param m: The largest number of items that can be remove
* @return: the result of the min item
*/
public int minItem(List<Integer> ids, int m) {
// write your code here
Map<Integer, Goods> counter = new HashMap<>();
for (Integer id : ids) {
Goods goods = counter.get(id);
if (goods == null) {
goods = new Goods(id);
counter.put(id, goods);
}
goods.addCount();
}
List<Goods> goodsList = new ArrayList<>(counter.values());
Collections.sort(goodsList);
Iterator<Goods> iterator = goodsList.iterator();
while (iterator.hasNext()) {
Goods goods = iterator.next();
if (goods.getCount() <= m) {
iterator.remove();
m -= goods.getCount();
} else {
break;
}
}
return goodsList.size();
}
/**
* 商品
*/
private class Goods implements Comparable<Goods> {
private final int id;
private Integer count = 0;
private Goods(int id) {
this.id = id;
}
public int getId() {
return id;
}
public int getCount() {
return count;
}
public void addCount() {
++this.count;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Goods goods = (Goods) o;
return id == goods.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public int compareTo(Goods o) {
int c = this.count.compareTo(o.count);
return c != 0 ? c : this.id - o.id;
}
}
}
最后说两句
非常感谢你阅读本文章,如果你觉得本文对你有所帮助,请留下你的足迹,点个赞,留个言,多谢~
作者水平有限,如果文章内容有不准确的地方,请指正。
希望小伙伴们都能每天进步一点点。
声明
本文由二当家的白帽子博客原创,转载请注明来源,谢谢~