【发布时间】:2019-07-01 23:54:29
【问题描述】:
给定一个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();
}
【问题讨论】:
-
那么如果 k=2 和 Array=[1,1,1,3,3,3],那么 p=1 的答案是什么?是2吗?
-
@mahbubcseju,我也不确定这个输入,考试只提供了 3 个样本输入。我试图先解决这些问题。