【问题标题】:How can I count these duplicate integers? [duplicate]我如何计算这些重复的整数? [复制]
【发布时间】:2019-04-29 06:18:27
【问题描述】:

我不能修改数组的内容,比如使用 Array.sort()。

这段代码的预期返回是 6,因为值 1 重复了三个,值 2 重复了一个,值 4 重复了两个。但我的显示为 10。我知道它是 10 的原因:它会多次计算重复项。

如何让这段代码只检查一次重复的整数?

private int count = 0;

public void run() {
    int[] a = {1, 4, 2, 4, 7, 1, 1, 9, 2, 3, 4, 1};
    println(countDuplicates(a));
}

private int countDuplicates(int[] a) {
    for (int i = 0; i < a.length; i++) {
        for (int j = i + 1; j < a.length; j++) {
            if (a[i] == a[j]) { 
                count++;
            }
        }
    }
    return count;
}

【问题讨论】:

  • 提示:使用Map&lt;Integer, Integer&gt; 从元素到元素的频率,并且只遍历你的数组一次,这个任务可以变得更容易。
  • 你也可以使用 set 实现,在 set 中添加 sth 时,你可以检查是否得到 true 或 false 并增加重复的计数器。
  • 我认为 (i) 应该达到 length-1
  • @K. Fred 遍历 for(int j = 0; j
  • 只计算到后面的第一个重复,然后突破j

标签: java arrays


【解决方案1】:

一种选择是将当前大小减去删除重复项的大小:

Set<Integer> set = new HashSet<>();
for (int i=0; i < a.length; ++i) {
    set.add(a[i]);
}

int numDuplicates = a.length - set.size();

在 Java 8 中使用流从原始 int 数组中填充一组 Integer 可能是一种时尚的方式。

【讨论】:

  • 好主意!虽然它可能不适用于 Algo 类。此外,还有很多盒装物品(并不是我太在意那个)。
  • 不确定这是否有效,假设int []a= {1,1,1,1},这个减法会不会返回 5 而不是 3?
  • 我的代码将为您的示例数组返回 3(4,原始数组的大小,负 1,集合的大小)。也就是说,它会报告 三个 重复,这对我来说似乎是正确的。
  • 我误以为您仍在使用问题中的一些代码。如果您使用 Set 来生成唯一值列表,则它在逻辑上遵循其余项目必须重复。这很聪明。
  • 嗯,我没学过'HashSet'或'set'(?)你能不使用它解释一下吗?
【解决方案2】:

这里有简单易懂的逻辑供学习者理解

public static void main(String[] args) throws IOException {
    int []a ={1, 4, 2, 4, 7, 1, 1, 9, 2, 3, 4, 1};

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

    for(int i = 0; i < a.length; i++) {
        //Check the is already occurred if not then add occurrence as 1
        if (!occurances.containsKey(a[i])) {
            occurances.put(a[i], 1);
        }
        // Second occurrences for a number
        else {
            occurances.put(a[i], occurances.get(a[i]) + 1);
        }
    }

    System.out.println(occurances);
    System.out.println("Total Numbers: "+a.length);
    System.out.println("Duplicate count is "+ (a.length - occurances.size()));
}

【讨论】:

    【解决方案3】:

    就地对数组进行排序。

    遍历数组一次,计算当前值等于前一个值的次数。

    (假设您可以使用库方法对数组进行排序)

    【讨论】:

    • 问题编辑后,此答案不适用。
    【解决方案4】:
    private static int countDuplicates(final int[] a)
    {
        int count = 0;
        Arrays.sort(a); // sort array, you can use any way for it
        for (int i = 0; i < a.length - 1; i++)
        {
            if (a[i] == a[i + 1]) // check only next element
            {
                count++;
            }
        }
        return count; // return 6
    }
    

    【讨论】:

    • 在编辑问题后,很明显 Arrays.sort(a) 是不允许的..
    • 谢谢!但我试图在没有排序的情况下解决它。
    猜你喜欢
    • 2022-01-03
    • 2020-12-20
    • 2015-03-04
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多