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

题目描述

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

题解

hash表法

  1. class Solution:
  2. def twoSum(self, nums: List[int], target: int) -> List[int]:
  3. record = dict()
  4. for i, num in enumerate(nums):
  5. if target-num in record:
  6. return [record[target-num], i]
  7. else:
  8. record[num] = i

排序双指针法

相关题目

3-sum 4-sum问题