首页 > 解决方案 > 无法通过“在数组中出现 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 个问题。

  1. 我了解虽然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%20seesJava 是“按引用传递”还是“按值传递”? . 所以我不能修改/返回 arr 的值而不重新分配它,因为我稍后需要使用“new”关键字。示例:我无法执行以下操作:

    tester(arr,1) //返回原始值,因为该方法在将 //arraylist 转换为数组时具有“新”。似乎也没有解决此问题的方法..

  2. 在编码挑战中,我也只通过了 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;
}

标签: javaarraystestingreference

解决方案


使用 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;
}

推荐阅读