Finding common minimum value between two arrays

白昼怎懂夜的黑 提交于 2019-12-19 04:50:18

问题


I am working on a problem in Javascript. Finding common minimum value between two arrays. However, I have been told that this might not work on some values. What is the issue?

function cmp(a, b) { return a - b; }

function findMinimum(A, B) {
    var n = A.length;
    var m = B.length;
    A.sort(cmp);
    B.sort(cmp);
    var i = 0;
    for (var k = 0; k < n; k++) {
        if (i < m - 1 && B[i] < A[k])
            i += 1;
        if (A[k] == B[i])
            return A[k];
    }
    return -1;
}

回答1:


Let's take,

A = [ 1, 3, 5, 7]
B = [ 0, 0, 1, 4, 6]

and run through your loop.

Your script fails.

The correct logic should be, you either increment i or k in 1 iteration. Not both

I would do something like,

for (var k = 0; k < n;) {
    if (A[k] == B[i])
        return A[k];

    if (i < m - 1 && B[i] < A[k])
        i += 1;
    else
        k += 1;
}



回答2:


I'd suggest changing your methodology here. Sorting both of the arrays at the beginning is expensive. Find the intersection set of two arrays and then sort it and return its mimimum value, that's all.




回答3:


This should work. Just replace the first if with a while. The while loop loops through array B till it finds an element which is greater than the minimum element of A. Then the outer for loop loops through A to find any element that matches the current element of B or till it reaches an element that is greater than the current element of B, where the process repeats.

function cmp(a, b) {
  return a - b;
}

function findMinimum(A, B) {
  var n = A.length;
  var m = B.length;
  A.sort(cmp);
  B.sort(cmp);
  var i = 0;
  for (var k = 0; k < n; k++) {
    while (i < m - 1 && B[i] < A[k])
      i += 1;
    if (A[k] == B[i])
      return A[k];
  }
  return -1;
}

findMinimum([1,3,5,7], [0,0,1,4,9]);  // 1
findMinimum([3,5,7,9], [1,2,4,7,10]); // 7


来源:https://stackoverflow.com/questions/31828623/finding-common-minimum-value-between-two-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!