java - 无法通过“在数组中出现 y 次后删除 x 元素”的测试用例
问题描述
我正在尝试通过编码挑战。目标是从数组中删除重复项(在定义的“第 n 次”时间之后)。
例如,
int[] arr;
arr = new int[] {1, 2, 2, 3, 3, 3, 4, 5, 5};
arr = tester(arr,1);//return 1,4. anything having more then 1 occurrence is removed from the //array
我这里有 2 个问题。
我了解虽然java主要是按值调用,但更详细:https ://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java#:~ :text=Longer%20answer%3A,object%20that%20the%20caller%20sees。Java 是“按引用传递”还是“按值传递”? . 所以我不能修改/返回 arr 的值而不重新分配它,因为我稍后需要使用“new”关键字。示例:我无法执行以下操作:
tester(arr,1) //返回原始值,因为该方法在将 //arraylist 转换为数组时具有“新”。似乎也没有解决此问题的方法..
在编码挑战中,我也只通过了 10 个测试用例中的 2 个,我不太清楚为什么。我还尝试使用字符串输入或长度 = 0 或 null 进行错误处理,但没有成功。(或者为了时间复杂性而在hashmap中实现它)我的逻辑似乎没有问题,我只是不确定测试用例是什么,因为它是隐藏的。
我相信部分挑战需要我将它返回到原始数组中,这意味着改变 arr 本身的值,但我无法找到不使用 new 关键字的方法。有什么想法吗?
public static int[] tester(int[] data, int n)
{
ArrayList<Integer> storeNon_dup = new ArrayList<Integer>();
//nested for loop to run through the array
//store in arrayList if criteria valid
for(int i = 0; i < data.length; i++)
{
int counter = 0;
for(int j = 0; j< data.length; j++)
{
if(data[i] == data[j])
{
counter++;
}
}
//if not duplicate in n-th occurence, add to list
if(counter<=n)
{
storeNon_dup.add(data[i]);
}
}
//convert arraylist to array
int[] container = new int[storeNon_dup.size()];
for(int i = 0; i<storeNon_dup.size(); i++)
{
container[i] = storeNon_dup.get(i);
}
return container;
}
解决方案
使用 HashMap 的替代解决方案。
public static List tester(int[] data, int n) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<data.length; i++) {
if(map.containsKey(data[i])) {
map.put(data[i], map.get(data[i])+1);
}else {
map.put(data[i], 1);
}
}
List lst = new ArrayList<Integer>();
for(Integer key : map.keySet()) {
if(map.get(key)<=n) {
lst.add(key);
}
}
return lst;
}
推荐阅读
- c# - 使用 FluentFTP 从 FTP 并发下载多个文件,最大值
- android - AWS Device Farm - java.lang.ClassNotFoundException:找不到类“androidx.test.runner.AndroidJUnitRunner”
- javascript - 设置保持正确数字输入的条件
- javascript - 如何在这个 React 组件中去抖动搜索功能?
- python - 如何在 Django Rest Framework 中的外键字段上使用过滤器
- javascript - 将数据挂载到 React 状态返回错误
- sql - 具有日期和类别维度的 SQL 表
- android - viewModelScope 在 viewPager 中被取消
- vba - Visual Basic 有没有限制变量可以像 C90 一样声明的位置?
- google-colaboratory - Colab - 如何将 CSV 下载到我计算机上的文件中