给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

    例子

    给定 nums = [2, 7, 11, 15], target = 9 返回 [0, 1]

    // 思路:通过差值来寻找(拓展:如果存在多组数值相加,符合条件的)

    1. var twoSum = function(nums, target){
    2. let res = []
    3. let temp = []
    4. for (let i = 0; i < nums.length; i++) {
    5. let dif = target - nums[i]
    6. if (temp[dif]!==undefined) {
    7. res.push(temp[dif], i)
    8. }
    9. temp[nums[i]] = i
    10. }
    11. return res
    12. }
    13. // 使用es6的map写法
    14. var twoSum = function(nums, target) {
    15. const map = new Map()
    16. for (let i = 0; i < nums.length; i ++) {
    17. const otherIndex = map.get(target - nums[i])
    18. if (otherIndex !== undefined) {
    19. return [otherIndex, i]
    20. }
    21. map.set(nums[i], i)
    22. }
    23. }