JS Two Sum


  • 0
    E

    One pass hashtable:

    var twoSum = function(nums, target) {
        var hashmap = new Array();
        
        for (var i = 0;i < nums.length;i++)
        {
            var complement = target - nums[i];
            if (hashmap.hasOwnProperty(complement) && hashmap[complement] != i)
            {
                return Array(hashmap[complement],i);
            }
            hashmap[nums[i]] = i;
            
        }
    };
    

    Start-end array:

    var twoSum = function(nums, target) {
        
        function sortNumber(a,b)
        {
            return a - b;
        }
    
        var hashmap = new Array();
        var res = new Array();
        for (var i=0; i<nums.length; i++){
            if (nums[i] * 2 == target){ res.push(i); }
            hashmap[nums[i]] = i;
        }
        
        if (res.length == 2){
            return res;
        }
        
        nums.sort(sortNumber);
        var start = 0;
        var end = nums.length-1;
        var sum = 0;
        var a,b;
        while (start<end)
        {
            sum = nums[start] + nums[end];
            if(sum < target){start++;}
    	    else if(sum > target){end--;}
    	    	else{
    	    			a = nums[start]; 
    	    			b = nums[end];
    	    			if (hashmap[a]>hashmap[b]) {return Array(hashmap[b],hashmap[a]);}
    	    			else {return Array(hashmap[a],hashmap[b]);}
    	    		}
        }
        
    }
    

Log in to reply
 

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