简体   繁体   English

使用javascript查找数组中任意两对元素之间的最小绝对差异时出错

[英]Error in finding minimum absolute difference between any two pair of elements in an array using javascript

I am trying to solve a program for finding minimum absolute difference between any pair of elements in an array using javascript. 我试图解决一个程序,使用javascript查找数组中任何元素对之间的最小绝对差异。 The input takes arguments as array elements. 输入将参数作为数组元素。 The output returns the minimum absolute difference between any two elements in an array 输出返回数组中任何两个元素之间的最小绝对差值

For example, input as [1,2,4] and the output is 1 例如,输入为[1,2,4],输出为1

The detailed description of the problem is given in this link. 问题的详细说明中给出这个链接。

In my code, when giving input array containing 1000 elements, it compiles and shows Terminated due to time out, but it works for smaller sized input arrays 在我的代码中,当给出包含1000个元素的输入数组时,它会因超时而编译并显示Terminated,但它适用于较小尺寸的输入数组

I think the error comes from the issues in performance and complexity . 我认为错误来自性能和复杂性方面的问题。 I researched for issue but I'm stuck with how to proceed further steps 我研究了问题,但我仍然坚持如何进一步的步骤

My code: 我的代码:

  var arr = [..] //array containing 1000 elements var count = minimumAbsoluteDifference(arr); console.log(count); function minimumAbsoluteDifference(arr) { var diff = []; var index = 0; arr.sort((a, b) => { return (a - b); }); for (var i = 0; i < arr.length-1; i++){ for (var j = i+1; j < arr.length; j++){ if (i != j) { diff[index] = Math.abs(arr[i] - arr[j]); console.log("index", i, j); index++; } } } var minAbsoluteDifference = Math.min(...diff); return minAbsoluteDifference; } 

After the array has been sorted, the minimum absolute difference between any two elements will necessarily be between two adjacent elements. 在对数组进行排序之后,任何两个元素之间的最小绝对差异必然在两个相邻元素之间。 So, you can change your nested for loops ( O(N^2) ) to a single for loop ( O(N) ) (though, the sort function is still O(N log N) , so overall complexity is only reduced to O(N log N) ): 因此,您可以将嵌套for循环( O(N^2) )更改为单个for循环( O(N) )(但是,排序函数仍为O(N log N) ,因此整体复杂性仅降低到O(N log N) ):

function minimumAbsoluteDifference(arr) {
    var diff = [];
    arr.sort((a, b) => a - b);
    for (var i = 0; i < arr.length - 1; i++) {
        if (i < arr.length - 1) {
            diff.push(Math.abs(arr[i] - arr[i + 1]));
        }
    }
    var minAbsoluteDifference = Math.min(...diff);
    return minAbsoluteDifference;
}

This would work in most situations, but another issue is that HackerRank appears to call this function with unreasonably huge arrays (eg, with 100000 items in a single array), so 这在大多数情况下都有效,但另一个问题是HackerRank似乎用不合理的巨大数组调用这个函数(例如,在单个数组中有100000个项目),所以

Math.min(...diff)

will result in 会导致

RangeError: Maximum call stack size exceeded RangeError:超出最大调用堆栈大小

Call Math.min on every iteration instead: 改为在每次迭代时调用Math.min

function minimumAbsoluteDifference(arr) {
    var lowestDiff = Infinity;
    arr.sort((a, b) => a - b);
    for (var i = 0; i < arr.length - 1; i++) {
        lowestDiff = Math.min(lowestDiff, Math.abs(arr[i] - arr[i + 1]));
    }
    return lowestDiff;

}

  for (var i = 0; i < arr.length - 1; i++) {
      var j = i+1;//only check the diff with next neighbor
      diff[index] = Math.abs(arr[i] - arr[j]);
      console.log("index", i, j);
      index++;
  }

This is a nice opportunity to use the Array.map method because it allows us access to the currentValue being iterated, the index of the iteration, and the array we're currently reducing. 这是使用Array.map方法的好机会,因为它允许我们访问正在迭代的currentValue,迭代的索引以及我们当前正在减少的数组。 Here's how the function would look: 这是函数的外观:

function minimumAbsoluteDifference(array) {
  const sortedArray = [...array].sort((a, b) => a - b);
  let difference = sortedArray[sortedArray.length - 1];

  sortedArray.map((currentValue, index, array) => {
    const currentMinDifference = Math.abs(currentValue - array[index + 1]);

    if (currentMinDifference < difference) {
      difference = currentMinDifference;
    }
  });

  return difference;
}

First, we sort the array to make it easier to work with and then we initialize the difference to be the largest item in the array. 首先,我们对数组进行排序以使其更易于使用,然后我们将差异初始化为数组中的最大项。

Then we call the map method on the sorted array with the provided callback taking the currentValue, index, and array as arguments. 然后我们使用提供的回调调用排序数组上的map方法,将currentValue,index和array作为参数。

Inside the map method is where we will calculate the absolute differences between the current number and the next. map方法中,我们将计算当前数字与下一个数字之间的绝对差异。 If the absolute difference for the current iteration is smaller than difference , then we've found a smaller absolute difference in the array. 如果当前迭代的绝对差值小于difference ,那么我们在阵列中发现了较小的绝对差值。

This goes on till the end. 这一直持续到最后。

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

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