Share my solution with javascript


  • 0
    H

    Share my solution with javascript
    how can be more efficient?

    var threeSum = function(nums) {
        var resultArr = [];
        for (var i = 0, len = nums.length; i < len - 1; i++) {
            var res = 0 - nums[i];
            for (var j = i + 1; j < len; j++) {
                var index  = nums.lastIndexOf(res - nums[j]);
                if (index !== -1 && index !== i && index !== j) {
                    var newItem = [nums[i], nums[j], res - nums[j]].sort();
                    var isExist = false;
                    if (resultArr.length > 0) {
                        for (var k = 0, lenArr = resultArr.length; k < lenArr; k++) {
                            var item = resultArr[k].sort();
                            if (item[0] === newItem[0] && item[1] === newItem[1] && item[2] === newItem[2]) {
                                isExist = true;
                                break;
                            }
                        }
                    }
                       
                    if (!isExist) {
                        resultArr.push(newItem);
                    }
                  
                }
            }
        }
        
        
        return resultArr;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.