首页 > 代码库 > leet code Two Sum

leet code Two Sum

/*
 * Example:
 * Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].

 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */

function twoSum(nums, target) {
  var len = nums.length;
  var indexnumber = [];
  for( var i = 0; i < len; i ++ ){
    var sub = target - nums[i]
    for( var j = 0; j < len; j ++ ){
      if( j != i && nums[j] == sub ){
        indexnumber.push(i,j)
      }
    }
  }
  var newnumbers = Array.from(new Set(indexnumber))
  var result = [];
  for( var i = 0 ; i < newnumbers.length ; i += 2 ){
    result.push(newnumbers.slice( i, i + 2 ))
  }
  return result
};

 

leet code Two Sum