Changing O (n ^ 3) to O (n ^ 2) in JavaScript

I am trying to wrap my head around saving time in my coding solution.

I have a function with a name tripletSumthat takes two parameters xand a, where xis a number, and ais an array.

This function should return trueif the list acontains three elements that contain a number x, otherwise it should return false.

I created the following working solution:

function tripletSum(x, a) {
    for(var i = 0; i < a.length; i++) {
        for(var j = i + 1; j < a.length; j++) {
            for(var k = j + 1; k < a.length; k++) {
                if((a[i] + a[j] + a[k]) === x) {
                    return true;
                }
            }
        }
    }
    return false;
}

But this does not seem to be the best practice. Currently, the time spent on performing this function is O(n^3), if I am not mistaken, and I think that it can be improved in order to have temporary complexity O(n^2).

Anyway, can I change this code to do this?

: , JavaScript, , .

+6
3

: a. , 0 N - 2 (). i . , . , "" "" ( + 1 N- ). 2 left right. left , right . left = i + 1 right = N - 1. sum a[i] + a[left] + a[right]. 3 :

  • If sum = x, true
  • sum > x, , right 1 ( )
  • sum < x, , left 1 ( )

Javascript.

function tripletSum(x, a) {
    a.sort(function(i, j) {
        return i - j;
    });

    var N = a.length;

    for(var i = 0; i < N - 2; i++) {
        var left = i + 1, right = N - 1;

        while(left < right) {
            var sum = a[i] + a[left] + a[right];
            if(sum === x) {
                return true;
            }
            else if(sum > x) {
                right--;
            }
            else {
                left++;
            }
        }

    }

    return false;
}

O(N^2) .

+2

, , , . x .

function tripletSum(x, a) {
    var dictionary = {};
    for(var i = 0; i < a.length; i++) {
        dictionary[a[i]] = true;
    }

    for(var i = 0; i < a.length; i++) {
        for(var j = i + 1; j < a.length; j++) {
            var remainder = x - a[i] - a[j];
            if(dictionary[remainder])
                return true;
        }
    }
    return false;
}
+4

, O (n ^ 2 * logn) O (n ^ 3).

function tripletSum(x, a) {
    a.sort(function(a, b) {
            return a - b
        }) // O(n*logn)
    var n = a.length;
    for (var i = 0; i < n; i++) {
        for (var j = i + 1; j < n; j++) {
            if (a.indexOf(x - a[i] - a[j]) > j) {
                return true; //O(n^2*logn)
            }
        }
    }
    return false;
}

console.log(tripletSum(0, [
    1,
    5,
    6,
    -2, 
    -3
]))
Hide result

= O (n * logn) + O (n ^ 2 * logn) ~ O (n ^ 2 * logn)

0
source

All Articles