【问题标题】:Find all pairs of elements in an array such that the absolute value of their difference is x查找数组中的所有元素对,使得它们的差值的绝对值为 x
【发布时间】:2017-10-18 16:55:17
【问题描述】:

我有一个未排序的数组,我想找到该数组中的所有对,以便它们的差值(绝对值)给出 x。

例如,如果 x=8 并且我们有数组 {13, 1,-8, 21, 0, 9,-54, 17, 31, 81,-46} 我会得到: 值为 13 和 21 的索引 0 和 3(例如,13-21= | 8 |) 值为 1 和 9 的索引 1 和 5 值为 -8 和 0 的索引 2 和 4 指数 6 和 10,值为 -54 和 -46

我做了一个解决方案,但我不确定它是 O(n) 还是 O(n^2)。我试图避免嵌套循环,而是保留两个指针 i 和 j,但我仍然认为它是 O(n^2)?它的行为有点像嵌套循环。

int i = 0;
int j = 1;

    System.out.println("All pairs of elements of the array that subtract exactly to absolute value of " + x + " are:");

    while (i < A.length && j < A.length)
    {
        if (abs(A[i] - A[j]) == x)
        {
            System.out.println("Indices " + i + " & " + j + " with values " + A[i] + " & " + A[j]);
        }

        if (j != A.length - 1)
        {
            j++;
        } else if (i == A.length - 1)
        {
            return;
        } else
        {
            i++;
            j = i + 1;
        }

    }

【问题讨论】:

  • 尝试发布到Code Review StackExchange
  • 为您的代码和嵌套循环打印出ij 的值。如果输出相同(如我所料),那么您就有答案了:您的代码是 O(n^2)。为了比 O(n^2) 做得更好,你需要一个不同的算法,例如首先对数组进行排序。
  • 欢迎来到 Stack Overflow!假设代码正常工作,您可能希望以更完整的方式编写您的示例,并在Code Review 寻求批评。请务必先阅读A guide to Code Review for Stack Overflow users,因为那里有些事情的做法不同!

标签: java arrays algorithm


【解决方案1】:

它有点像嵌套循环

这不仅仅是“某种”——您已经手动编写了两个循环,j-循环逻辑上位于 i-循环内。关键部分是:

i = 0
while i < limit {
    ...
    i += 1
}

j = 1
while j < limit {
    ...
    j = i+1
}

每一个都是 for 循环的“while”-ish 版本。

这与您的 if-else 逻辑相结合,可以很好地转换为

for i in 0 : limit {
    for j in i+1 : limit {
    }
}

【讨论】:

    【解决方案2】:
    1. 你可以使用map来索引你的数组值,然后计算目标值的补码,并在map中搜索补码的索引,即O(1),将值插入map是O(n),所以时间复杂度可以简化为O(1),代码sn-p如下所示

    导入 java.util.*;

    公共类 TwoDiff {

    public static void main(String args[])
    {
        int arr[] = {13, 1,-8, 21, 0, 9,-54, 17, 31, 81,-46};
        int target = 8;
        List<int[]> res = twoDiff(arr, target);
        res.forEach(l -> System.out.println(Arrays.toString(l)));
    }
    
    private static List<int[]> twoDiff(int[] arr, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        List<int[]> resList = new ArrayList<>();
        for(int i=0; i< arr.length; i++)
        {
            map.put(arr[i], i);
        }
        for (int i =0; i < arr.length; i++)
        {
            int complement = arr[i] - target;
            if(map.containsKey(complement))
            {
                resList.add(new int[] {i, map.get(complement)});
            }
        }
        return  resList;
    }
    

    }

    【讨论】:

      猜你喜欢
      • 2020-02-22
      • 2014-11-08
      • 2019-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-30
      • 1970-01-01
      相关资源
      最近更新 更多