1.两数之和 - 图1

1. for循环解法

  1. var twoSum = function (nums, target) {
  2. let len = nums.length
  3. let res = []
  4. for (let i = 0; i < len; i++) {
  5. let x = target - nums[i]
  6. for (let j = i + 1; j < len; j++) {
  7. if (nums[j] == x) {
  8. res = [i, j]
  9. }
  10. }
  11. }
  12. return res
  13. };
  14. console.log(twoSum([2, 7, 11, 15], 9));

2. 巧用map解法

1.用map来存放{数组元素值,坐标}这样的键值对2.运用逆向解法,即用target减去数组中的某个元素,然后来判断map中是否有相同的值,若有则存在满足条件的答案,返回两个坐标即可;若没有,则保存{数组中某个元素值,对应的坐标}到map对象中。依次遍历即可判断是否有满足条件的两个元素。

  1. var twoSum = function (nums, target) {
  2. let len = nums.length
  3. let map = new Map()
  4. for (let i = 0; i < len; i++) {
  5. let x = target - nums[i]
  6. if (map.has(x)) {
  7. return [map.get(x), i]
  8. }
  9. map.set(nums[i], i)
  10. }
  11. };