Two Sum (javascript) not accepting correct answer


  • 0
    J

    For my code, this works perfectly in repl.it, but here I keep getting a completely different output. Any suggestions?

    on repl.it, the output for twoSum([3,3], 6) is [ 0, 1 ], but when leetcode tests, I get [1,2,0,1] as the output. Not sure how this is even possible since there is no 2 index position in the input.

     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
    
    let newArray = []
    var twoSum = function(nums, target) {
        for(let i = 0;i < nums.length - 1; i++){
            for(let j = 1; j < nums.length;j++){
                if (nums[i] + nums[j] === target){
                    newArray.push(i,j)
                    return newArray
                }
            }
        }  
    };

  • 0
    H
    /**
     * @param {number[]} nums
     * @param {number} target
     * @return {number[]}
     */
    var twoSum = function(nums, target) {
        for(let i = 0; i < nums.length; i++){
    		for(let j = 1; j < nums.length; j++){
    			if(nums[i] + nums[j] == target){
    				if(i !== j){
    					return [i, j];
    				}
    			}
    		}
    	}
    };
    

Log in to reply
 

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