noodleProblems/
Two Sum
#01

Two Sum

AlgorithmeasyArrayHash Table
New York Times

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

Each input has exactly one solution, and you may not use the same element twice. Return the indices in ascending order.

Example cases

  • basic
    in nums = [2,7,11,15], target = 9
    out [0,1]
    nums[0] + nums[1] = 2 + 7 = 9.
  • middle pair
    in nums = [3,2,4], target = 6
    out [1,2]
    nums[1] + nums[2] = 2 + 4 = 6.
  • duplicates
    in nums = [3,3], target = 6
    out [0,1]
  • negatives
    in nums = [-1,-2,-3,-4,-5], target = -8
    out [2,4]

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Exactly one valid answer exists.
Saved
nums =
[2,7,11,15]
target =
9