【问题标题】:Finding Duplicate numbers in a sorted Array在有序数组中查找重复数字
【发布时间】:2022-01-03 06:34:01
【问题描述】:

我想知道是否有任何方法可以找出排序数组中有多少对 最简单的方法是使用两个 for 循环

 for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[i] == arr[j])

但关键是这两个 for 循环即使在未排序的数组中也有效 如果我们的数组是排序的,有没有办法找到只有一个 for 或 while 循环的对? 示例可以是 {1, 1, 1, 2, 3, 3} 它有 4 对 [0][1], [0][2], [1][2], [4][5]

【问题讨论】:

  • 在排序后的数组中只需要比较相邻的元素。只需要一个循环。
  • 请澄清标题:重复和“对”不是一回事。还有多少对:`1 2 2 2 3' 有多少对?
  • @Andy 在你的例子中它有 3 对索引 [1] [2] , [1] [3], [2][3]

标签: java arrays for-loop while-loop


【解决方案1】:

好吧,您需要遍历数组并计算连续相同的数字。如果遇到不同的数字,则需要计算最后看到的数字的对数。对于每个不同的数字,您都需要这样做。

在下图中,您可以看到三个相同数字的子序列

     a      b    c
  ┌──┴──┐  ┌┴─┐  │
  │     │  │  │  │
[ 1, 1, 1, 2, 2, 3 ]

让我们首先定义一种方法来计算特定计数的对数。它的公式总是

⠀⠀⠀⠀⠀⠀?² − ?
?(?)⠀=⠀──────
⠀⠀⠀⠀⠀⠀⠀⠀2

int countPairs(int number) {
    return number * (number - 1) / 2;
}

然后让我们编写遍历数组的方法。我在代码中添加了 cmets 来解释发生了什么:

int countPairs(int[] array) {
    // If our array is empty or contains a single element, then there are no
    // pairs, obviously
    if (array.length < 2) {
        return 0;
    }

    // We keep track of the total number of pairs here
    int totalPairs = 0;

    // We also keep track of the number of consecutive identical numbers.
    int consecutive = 1;

    // We begin our index with 1, since we need to compare it to the previous one
    // (and we don't want an ArrayIndexOutOfBoundsException to be thrown)
    for (int i = 1; i < array.length; i++) {
        if (array[i] == array[i - 1]) {
            // If the encountered number is the same as the previous one,
            // then increment the subsequence counter
            consecutive++;
        }
        else {
            // If the number is different than the previous one, then a new subsequence
            // has started. We need to process the previous subsequence. Calculate the
            // number of pairs, add it to the result, and then reset `consecutive`
            totalPairs += countPairs(consecutive);
            consecutive = 1;
        }
    }
    // At last, process the last sequence
    totalPairs += countPairs(consecutive);
    return totalPairs;

【讨论】:

    【解决方案2】:

    好吧,您不必将每个元素与其他元素进行比较(两个嵌套的 for 循环所做的),而只需比较相邻的元素...

    int paires = 0;
    for(int i = 0; i < arr.lenght - 1; i++) {
       if(arr[i] == arr[i + 1]) paires++; // Test if the i-th element is equal to the i+1-th element and increasing counter if so.
    }
    

    注意for循环只能运行到n-1个元素,否则会出现空指针异常

    【讨论】:

    • arr = {1, 1, 1, 2, 3, 3} 返回 3,而不是 4。
    【解决方案3】:

    试试这个。

    static int combination(int start, int end) {
        int size = end - start;
        return size * (size - 1) / 2;
    }
    
    static int countDuplicatedNumberPairs(int[] arr) {
        int length = arr.length, count = 0;
        if (length <= 0) return count;
        int start = 0, previous = arr[0];
        for (int i = 1; i < length; ++i)
            if (arr[i] != previous) {
                count += combination(start, i);
                start = i;
                previous = arr[i];
            }
        count += combination(start, length);
        return count;
    }
    
    public static void main(String[] args) {
        int[] arr =  {1, 1, 1, 2, 3, 3} ;
        System.out.println(countDuplicatedNumberPairs(arr));
    }
    

    输出:

    4
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 2018-06-01
      • 1970-01-01
      • 2015-06-14
      • 2016-08-15
      • 2018-01-21
      • 1970-01-01
      相关资源
      最近更新 更多