有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java数组查找重复项并替换它们

public static int[] isthereDuplicates(int[] combination) {
    Set<Integer> foundedNumbers = new HashSet<>();

    for (int i= 0; index < combination.length; i++) {
        if (foundedNumbers.contains(combination[i])) {
                combination[i] -= 1;
        } else {
            foundedNumbers.add(combination[i]);
        }

    return combination;
}

我需要找到并替换数字数组中的重复项。数字数组也由1到40之间的7个数字随机选择而成。如果我有一个副本,我展示的代码可以工作,但是当我有几个副本时,例如,我有1,14,20,1,38,1,5。中间1的值将更改,但第二个1的值将保持不变


共 (2) 个答案

  1. # 1 楼答案

    我相信这解决了你的问题:

    首先,确定数组中的数字,并将其记录为尚未找到

    然后你把这些数字看一遍,当你找到一个还没有找到的数字时,你就把它标记为找到了

    当你再次找到这个数字时,你可以用它做任何你想做的事情(在这个例子中,我把它设为-1)

    public static int[] duplicates(int[] combination) {
                HashMap<Integer, Boolean> foundNumbers = new HashMap<>();
                for (int i : combination) {
                    if(foundNumbers.containsKey(i)) continue;
                    foundNumbers.put(i, false);
                }
    
                for (int i = 0; i < combination.length; i++) {
                    if(!foundNumbers.get(combination[i])) {
                        foundNumbers.put(combination[i], true);
                    } else {
                        combination[i] = -1;
                    }
                }
    
                return combination;
            }
    
  2. # 2 楼答案

    您的代码似乎只需稍加修改和位转换即可工作

    public static int[] imaliDuplikata(int[] combination) {
        Random r = new Random();
        Set<Integer> foundeNumbers = new HashSet<>();
    
        for (int i = 0; i < combination.length; i++) {
            if (foundeNumbers.contains(combination[i])) {
                combination[i] = r.nextInt(40);
            } else {
                foundeNumbers.add(combination[i]);
            }
    
        }
        return combination;
    }
    

    以这种方式执行:

    int[] i = {1,14,20,1,38,1,5};
    System.out.println(Arrays.toString(imaliDuplikata(i)));
    

    您将获得所有重复数字的替换

    各种处决:

    [1, 14, 20, 0, 38, 35, 5]
    [1, 14, 20, 11, 38, 1, 5]
    [1, 14, 20, 22, 38, 30, 5]
    [1, 14, 20, 37, 38, 39, 5]