1. Two Sum
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. You can return the answer in any order.
Example 1nums = [2, 7, 11, 15], target = 9 → [0, 1]
2 + 7 = 9, so the indices are 0 and 1.
2 + 7 = 9, so the indices are 0 and 1.
Example 2nums = [3, 2, 4], target = 6 → [1, 2]
Constraints
- 2 ≤
nums.length≤ 10⁴ - −10⁹ ≤
nums[i]≤ 10⁹ - −10⁹ ≤
target≤ 10⁹ - Exactly one valid answer exists.
Follow-up: can you do it in better than O(n²) time?
Files in this pad
solution.py — your workdebug.py — a function with a small bugoptimize.py — a function that works but is wasteful
Python 3
Test cases
nums = [2, 7, 11, 15], target = 9
nums = [3, 2, 4], target = 6
nums = [3, 3], target = 6
Output
Run your code to see the result.