Leetcode-0001 sum of two numbers

Time:2020-4-24

Title address: https://leetcode-cn.com/problems/two-sum/

1. Violent solution

Direct double cycle, all possible solutions are given. The time complexity is O (n ^ 2), and the space complexity is O (1)

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

2.HashTable

  • The first loop places each number in the array nums in the map
  • The second loop determines whether target – nums [i] is in the map

Time complexity O (n), space complexity O (1)

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

  Throw new error ('There are no such two numbers')
}

3. Hashtable optimized version

A cycle, first check whether the map containstarget - nums[i], if it is found, it is the result we want; if not, put this nums [i] in the map, and continue the next cycle. This solution has only one cycle, so the time complexity is better than solution 2

Time complexity O (n), space complexity O (n)

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

  Throw new error ('There are no such two numbers')
};

For more knowledge of leetcode problem solving and data structure, please pay attention to my GitHub: https://github.com/guolizhi/

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]