简体   繁体   English

给定一个由 N 个整数组成的数组 A,返回最大的整数 K>0,使得数组 A 中同时存在 K 和 -K(相反的数)

[英]given an array A of N integers, return the largest integer K>0 such that both K and -K(the opposite number) exist in array A

Write a function solution, given an array A of N integers, return the largest integer K>0 such that both K and -K(the opposite number) exist in array A. If there is no such number the function should return 0.写一个函数解,给定一个由 N 个整数组成的数组 A,返回最大的整数 K>0,使得数组 A 中存在 K 和 -K(相反的数)。如果没有这样的数,函数应该返回 0。

Example:
1. Given A = [3,2,-2,5,-3], the function should return 3.
2. Given A = [1,2,3,-4], the function should return zero.

boolean found = false;
        int[] ar = { -5, -4, -1, -5, -4 };
        Arrays.sort(ar);
        for (int i = ar.length - 1; i >= 0; i--) {
            for (int j = 0; j <= ar.length - 1; j++) {
                if (ar[i] + ar[j] == 0) {
                    System.out.println(Math.abs(ar[i]));
                    found = true;
                    break;
                }
            }
            if (found == true) {
                break;
            }
        }
        if (found == false) {
            System.out.println("0");
        }
    }

Can someone please review the solution for time complexity and share your comments.有人可以查看时间复杂度的解决方案并分享您的意见。

Also, i need some help for same question in C# (me having no experience in C#)另外,我需要一些关于 C# 中相同问题的帮助(我没有 C# 经验)

Your current solution has O(n**2) time complexity since the solution uses nested loops:您当前的解决方案具有O(n**2)时间复杂度,因为该解决方案使用嵌套循环:

 for (int i = ar.length - 1; i >= 0; i--) {    // O(n)
   for (int j = 0; j <= ar.length - 1; j++) {  // O(n)
     ...

Here这里

 O(n) * O(n) = O(n**2)

You can try hashing (let it be Linq C# ) for O(n) time complexity您可以尝试对O(n)时间复杂度进行散列(让它成为Linq C#

  1. Given an array, say { 3, 2, -2, 5, -3 }给定一个数组,比如{ 3, 2, -2, 5, -3 }
  2. We can group by absolute values: 3 : {3, -3}, 2 : {2, -2}, 5 : {5}我们可以按绝对值分组: 3 : {3, -3}, 2 : {2, -2}, 5 : {5}
  3. Then filter to keep the groups with 2 distinct items: 3 : {3, -3}, 2 : {2, -2}然后过滤以保留具有 2 个不同项目的组: 3 : {3, -3}, 2 : {2, -2}
  4. Finally, we should take the max key: 3最后,我们应该取最大键: 3

Code:代码:

private static int MySolution(IEnumerable<int> array) => array
  .GroupBy(item => Math.Abs(item))                // O(n) 
  .Where(group => group.Distinct().Count() == 2)  // O(n)
  .Select(group => group.Key)                     // O(n) 
  .DefaultIfEmpty()                               // O(1)
  .Max();                                         // O(n)

Here这里

O(n) + O(n) + O(n) + O(1) + O(n) = O(n) 

Demo:演示:

  int[][] tests = new int[][] {
    new int[] { 1, 2, 3, -4 },
    new int[] { 3, 2, -2, 5, -3 },
    new int[] { 3, 2, -2, 5, 3 },  // no -3, but 3 appears twice
    new int[] { }
  };

  string result = string.Join(Environment.NewLine, tests
    .Select(test => $"{("[" + string.Join(", ", test) + "]").PadRight(20)} => {MySolution(test)}"));

  Console.Write(result);

Outcome:结果:

[1, 2, 3, -4]        => 0
[3, 2, -2, 5, -3]    => 3
[3, 2, -2, 5, 3]     => 2
[]                   => 0

Just the Array.sort will raise your time complexity to as much as O(n^2).只是Array.sort会将您的时间复杂度提高到 O(n^2)。 Best case O(n logn)最佳情况 O(n logn)

Source: https://www.baeldung.com/arrays-sortobject-vs-sortint来源: https : //www.baeldung.com/arrays-sortobject-vs-sortint

I will argue that you don't need it at all.我会争辩说你根本不需要它。 Remove it and just don't compare for i==j in your second loop.删除它,只是不要在第二个循环中比较 i==j 。

The two for loops will cause a complexity of O(n^2) as you do a full scan for each value in your worst case scenario where there are no matches.这两个 for 循环将导致 O(n^2) 的复杂性,因为您在没有匹配项的最坏情况下对每个值进行全面扫描。 So even if you totally remove the sorting, you are still at the same bad performance.因此,即使您完全删除排序,您的性能仍然很差。

You can make it better by starting always at the next element from the previous once you checked.您可以通过检查后始终从上一个元素的下一个元素开始来使其更好。

Food for thought: You can also add complexity in terms of space and just find the answer in one iteration from all the items.深思熟虑:您还可以增加空间方面的复杂性,只需在一次迭代中从所有项目中找到答案。 Retrieval from a Hasmap or a Hashset is O(1).从 Hasmap 或 Hashset 中检索是 O(1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM