The sum of two Numbers

Violence law

Time :O(n^2) Space :O(1)

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

Use map to save records

Time complexity :O(n) Space complexity :O(n)

var twoSum = function(nums, target) {
    const map = new Map()
    for (let i = 0; i < nums.length; i++) {
        if (map.has(nums[i])) {
            return [map.get(nums[i]), i]
        } else {
            map.set(target - nums[i], i)
        }
    }
    return []
};
Copy the code