查找两个数组之间的公共最小值 [英] Finding common minimum value between two arrays
问题描述
我正在处理Javascript中的问题。查找两个数组之间的公共最小值。但是,有人告诉我,这可能不适用于某些值。有什么问题?
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;
}
推荐答案
这应该有效。只需用替换第一个
。 if
,而而
循环遍历数组B,直到找到一个大于A的最小元素的元素。然后外部为
循环遍历A以查找与B的当前元素匹配的任何元素,或者直到它到达大于B的当前元素的元素,其中该过程重复。
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
这篇关于查找两个数组之间的公共最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!