给定一个整数数组N。遍历整个数组,选出 K 个包含相同值的位置。K然后从阵列中删除这些选定的。如果我们无法选择K值,则无法从数组中删除任何位置。
任务是最小化每次迭代后数组中可用的不同整数的数量。
对于给定的Q查询,每个查询都有一个数字P。对于每个查询,在进行迭代后打印数组中存在的不同整数的数量P。
1<= N <= 10^6
1<= K <= 10
1<= Q <= 10^5
0<= C <= 10^5
1 <= P <= N
Example:
N=5
K=1
Q=3
Array = [5,0,1,2,1];
Queries (Various P values):
1
5
3
Output:
3
0
1
P = 3时的解释:
1. First iteration, we can remove element 1 with value `5`.
2. Second iteration, we can remove element 2 with `0`.
3. Third iteration, we can remove element 4 with value `2`.
最后数组只包含两个具有值的元素1。所以剩下的不同颜色数是 1。
这是我尝试过的代码,但在如何满足要求方面遇到了困难:
static int getDistinctFeatures(int[] array, int size, int K, int P) {
Map<Integer, Integer> map = new LinkedHashMap<>();
// Count the occurrence of each element in the array
for (int i : array) {
map.put(i, map.getOrDefault(i, 0) + 1);
}
Set<Integer> keys = map.keySet();
List<Integer> keyList = new ArrayList<>(keys);
int index = 0;
for (int i = 0; i < P && index < keyList.size(); i++) {
int key = keyList.get(index);
index++;
int count = map.get(key);
if (count == 1) {
map.remove(key);
} else {
// What to do here
}
}
return map.size();
}
至尊宝的传说
白衣染霜花
慕桂英3389331
相关分类