JavaScript leetcode : two sum

js leetcode : two sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
console.log(twoSum([2, 7, 11, 15],22));//[1, 3]
console.log(twoSum([2, 7, 11, 15],9));//[0, 1]

方法一:

function twoSum(nums, target) {
  var len = nums.length
  var sum;
  var result;
    for(var i = 0; i <len; i++ ){
       for(var j = i+1 ; j < len ; j++){
        sum = nums[i] + nums[j]
        if ( sum === target) {
          result = [i,j]
          return result;
        }
       }
    }
};

方法二:

function twoSum(nums, target) {
    var len = nums.length;
    var obj = {}
    for(var i = 0; i < len; i++){
       if (obj[target - nums[i]] !== undefined){
           return [obj[target-nums[i]], i];
       }
      obj[nums[i]] = i
    }
};
posted @ 2017-11-09 20:36  芒果夏夏  阅读(112)  评论(0编辑  收藏  举报