简体   繁体   English

我对最小差分算法问题的解决方案是否具有最佳时空复杂度 (O(nLog(n) + mLog(m)))?

[英]Does my solution to the Smallest Difference algorithm problem have optimal space time complexity (O(nLog(n) + mLog(m)))?

Question :问题 在此处输入图像描述

Here is my solution:这是我的解决方案:


function smallestDifference(arrayOne, arrayTwo) {

    const combinedArray = [...arrayOne, ...arrayTwo];
    
    combinedArray.sort((a, b) => a - b);
    
    let smallestDifference = Infinity;
    let arrayOneInt = null;
    let arrayTwoInt = null;
    
    for (let i = 0; i < combinedArray.length - 1; i++) {
        if (Math.abs(combinedArray[i] - combinedArray[i+1]) < smallestDifference) {
            if (arrayOne.includes(combinedArray[i]) && arrayTwo.includes(combinedArray[i+1])) {
                smallestDifference = Math.abs(combinedArray[i] - combinedArray[i+1]);
                arrayOneInt = combinedArray[i];
                arrayTwoInt = combinedArray[i+1];
            } else if (arrayOne.includes(combinedArray[i+1]) && arrayTwo.includes(combinedArray[i])) {
                smallestDifference = Math.abs(combinedArray[i] - combinedArray[i+1]);
                arrayOneInt = combinedArray[i+1];
                arrayTwoInt = combinedArray[i];
            }
        }
    }
    
    return [arrayOneInt, arrayTwoInt];
}

Here is the given optimal solution这是给定的最佳解决方案


function smallestDifference(arrayOne, arrayTwo) {
  arrayOne.sort((a, b) => a - b);
    arrayTwo.sort((a, b) => a - b);
    let idxOne = 0;
    let idxTwo = 0;
    let smallest = Infinity;
    let current = Infinity;
    let smallestPair = [];
    while (idxOne < arrayOne.length && idxTwo < arrayTwo.length) {
        let firstNum = arrayOne[idxOne];
        let secondNum = arrayTwo[idxTwo];
        if (firstNum < secondNum) {
            current = secondNum - firstNum;
            idxOne++;
        } else if (secondNum < firstNum) {
            current = firstNum - secondNum;
            idxTwo++;
        } else {
            return [firstNum, secondNum]
        }
        if (smallest > current) {
            smallest = current;
            smallestPair = [firstNum, secondNum];
        }
    }
    return smallestPair;
}

For the above given optimal solution, it says the time complexity is O(nLog(n) + mLog(m)) and space complexity is O(1).对于上面给出的最优解,时间复杂度为 O(nLog(n) + mLog(m)),空间复杂度为 O(1)。 Does my solution above it also match this time complexity?我上面的解决方案是否也符合这个时间复杂度?

You have loop over combinedArray which has lenght N + M. Within this loop you have arrayOne.includes and arrayTwo.includes with O(N) and O(M) time complexities.您循环了长度为 N + M 的combinedArray 。在此循环中,您有arrayOne.includesarrayTwo.includes ,时间复杂度为 O(N) 和 O(M)。

So you have at least O((N + M) ^ 2) which is bigger than O(n Log(m) + m Log(n))所以你至少有O((N + M) ^ 2)大于O(n Log(m) + m Log(n))

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

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