1

我尝试使用 Java 解决这个问题,由于某种原因,9 个测试用例中只有 2 个通过,但在本地我所有的测试用例都通过了。我 99% 肯定 Google Foobar Java 测试用例在这个挑战中存在一些问题。是否有人遇到过这个问题,如果是,你做了什么来解决它?

问题是...

Write a function called solution(data, n) that takes in a list of 
less than 100 integers and a number n, and returns that same list 
but with all of the numbers that occur more than n times removed 
entirely. 

The returned list should retain the same ordering as the original 
list - you don't want to mix up those carefully-planned shift 
rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1,
solution(data, n) would return the list [5, 15, 7] because 10 occurs 
twice, and thus was removed from the list entirely.

-- Java cases --
Input:
Solution.solution({1, 2, 3}, 0)
Output:
    

Input:
Solution.solution({1, 2, 2, 3, 3, 3, 4, 5, 5}, 1)
Output:
    1,4

There are 6 more test cases that are hidden.

以下是我创建的解决方案。

public class MinionShift {
    public static int[] solution(int[] data, int n) {
        if(n<1)
            return new int[0];

        if(data.length < 1)
            return data;

        Map<Integer, Integer> map = new HashMap<>();

        for(int d: data) {
                map.put(d, map.getOrDefault(d, 0) + 1);
        }

        return Arrays.stream(data).filter(c->map.containsKey(c) && !(map.get(c)>n)).toArray();
    }
}

我尝试过的测试用例...

[{1, 2, 3}, 0]
[{1, 2, 2, 3, 3, 3, 4, 5, 5}, 1]
[{1, 2, 2, 3, 3, 3, 4, 5, 5}, 10]
[{1, 2, 2, 3, 3, 3, 4, 5, 5}, -1]
[{}, 5]
[{1, 1, 1, 1, 1}, 5]
[{101, 102, 103, 104, 105}, 5]

编辑... 我尝试了一个基于 Java 流的解决方案,但不幸的是,当我提交了一个 Python 解决方案时,挑战就消失了。但我还是把它贴在这里。

public class MinionShift {
    public static int[] solution(int[] data, int n) {
        if(n<1)
            return new int[0];

        if(data.length < 1)
            return data;

        return Arrays.stream(data).filter(d->Arrays.stream(data).filter(i->i==d).count()<=n).toArray();
    }
}
4

1 回答 1

0

这就是我让它工作的方式,你必须用数组向后工作。您需要创建另一个数组来检查重复项以记住它们。

public static int[] solution(int[] data, int n){
    if(n < 1){
        return new int[0];
    }

    if(data.length < 1){
        return data;
    }

    List<Integer> a = Arrays.stream(data).boxed().collect(Collectors.toList());

    for(int i = a.size()-1; i > -1; i--){
        ArrayList<Integer> t = new ArrayList<>();

        for(int j = 0; j < a.size(); j++){
            if(a.get(j) == a.get(i)){
                t.add(j);
            }
        }


        if(t.size() > n){
            for(int j = t.size()-1; j > -1; j--){
                a.remove((int) t.get(j));
            }

            i -= t.size()-1;
        }
    }

    data = new int[a.size()];
    int c = 0;
    for(int d : a){
        data[c] = d;
        c++;
    }

    return data;
}
于 2021-08-13T17:20:52.353 回答