To solve this problem, we need to find the indices of two numbers in an array such that their sum equals a given target. The solution should be efficient, both in terms of time and space.
Approach
The key insight here is to use a hash map (dictionary) to keep track of the numbers we have seen so far and their indices. This allows us to check for the complement of the current number (i.e., target - current number) in constant time. Here's the step-by-step approach:
- Initialize a dictionary: This will store the value of each number as the key and its index as the value.
- Iterate through the array: For each number, compute its complement (target minus the current number).
- Check for the complement: If the complement exists in the dictionary, return the indices of the complement and the current number.
- Store the current number: If the complement does not exist, add the current number and its index to the dictionary.
This approach ensures that we only traverse the array once, leading to an O(n) time complexity, where n is the length of the array. The space complexity is O(n) in the worst case, as we might store all elements in the dictionary.
Solution Code
def twoSum(nums, target):
seen = {}
for index, num in enumerate(nums):
complement = target - num
if complement in seen:
return [seen[complement], index]
seen[num] = index
return [] # According to problem statement, this line is unreachable
Explanation
Let’s break down the solution using an example:
- Example:
nums = [2,7,11,15],target =9- For
index=0(num=2), complement is9-2=7(not inseen→ add2:0toseen). - For
index=1(num=7), complement is9-7=2(exists inseen→ return[0, 1]).
- For
Another example: nums = [3,2,4], target=6
index=0(num=3): complement3not inseen→ add3:0.index=1(num=2): complement4not inseen→ add2:1.index=2(num=4): complement2exists → return[1,2].
This solution handles all edge cases, including negative numbers, zero, and duplicate values (as long as they are different elements). It efficiently finds the solution in linear time, making it optimal for large arrays.
Answer: The function twoSum returns the required indices. For example, if the input is nums = [2,7,11,15] and target=9, the output is [0, 1]. The code is as provided above.


作者声明:本文包含人工智能生成内容。