Can someone help me optimize my answer's runtime


  • 0
    J

    Can someone help me optimize my answer's runtime? I checked other answers on different program languages, they did same check. But my code costs too much time.

    /**
     * @param {number[]} nums
     * @return {number[][]}
     */
    var threeSum = function(nums) {
        nums = nums.sort(sortNum);
        l = nums.length;
        if(l < 3){
            return [];
        }
        r = [];
        for(i=0; i<l-2; i++){
            if( nums[i] > 0 ){
                break;
            }
            if( i > 0 && nums[i] == nums[i-1]){
                continue;
            }
            for(j=i+1; j<l-1; j++){
                if( nums[i] + nums[j] > 0 ){
                    break;
                }
                if( j>i+1 && nums[j] == nums[j-1]){
                    continue;
                }
                for(k=j+1; k<l;k++ ){
                    sum = nums[i] + nums[j] + nums[k];
                    if(sum == 0){
                        r.push ([nums[i],nums[j],nums[k]]);
                        break;
                    }else if(sum > 0){
                        break;
                    }else{
                        
                    }
                }
            }
        }
        
        return r;
    };
    
    var sortNum = function(a, b){
        return a-b;
    }
    

Log in to reply
 

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