Problem
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solution
Basic idea
Use a hash table to map value to indice. We can iterate values of array, put each value and its indice into the hash table, and check whether the complement exists in the hash table. If the complement in the hash table, return two indices.
Python implementation
|
|
Time complexity analysis
Traverse the array only once, O(n).
Space complexity analysis
Use hash table to store value and indices. For a list containing n values, the hash table will store at most n elements, O(n).
Link
1. Two Sum
1. 两数之和
(中文版) 算法笔记: 力扣#1 两数之和
近期评论