lf7817/leetcode

1. two sum

Closed this issue · 3 comments

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].
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {

};

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {

};

Beat: 44.34%
Runtime: 120ms
Time Complexity : O(n²)
Space Complexity: O(1)

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

Beat: 100.00%
Runtime: 52ms
Time Complexity : O(n)
Space Complexity: O(n)

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  const obj = {};
  
  for(let i = 0; i < nums.length; i ++) {
    const tmp = target - nums[i];
    
    if (obj.hasOwnProperty(nums[i])) {
      return [obj[nums[i]], i]
    }
    
    obj[tmp] = i;
  }
};