1. Two Sum ( JavaSctipt )

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].

解析:

  • 第一种简单粗暴的方法是直接两个循环,但是这样时间复杂度是时间复杂度 O(n^2)
  • 第二种方法只需要循环一次,时间复杂度O(n):
    1. 声明一个对象,key 是数组元素的值,value 是该值索引
    2. 循环数组,将 target 减去当前循环到的值,得到我们需要找的那个数
    3. 去对象里找是否有这个数,没有的话就添加到对象里
    4. 有就可以直接返回 value

(The following English translation may not be right -.-)

analyze:

  • The first solution is Nesting a loop in a loop,but the time complexity will be O(n^2)
  • The second only loop once:
    1. Declare an object,the key is the value of the array, the value is the index of the array's value
    2. Loop the array, get the value we need by the target subtract the 「array[index]」.
    3. return the value in the object or add the value into the object.
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let map = {}
    for (var i = 0; i <= nums.length; i++) {
        if (map.hasOwnProperty(target - nums[i])) {
            return [map[target - nums[i]], i]
        }
        map[nums[i]] = i
    }
};

你可能感兴趣的:(1. Two Sum ( JavaSctipt ))