This question is easy and …not that easy for me.
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].
At first time I try to only use list to solve it:
for i in range(len(nums)):
target = target - nums[i]
new_nums = nums
new_nums.pop(i)
if target in new_nums:
result.append(i)
result.append(nums.index(target))
print(result)
But the nums would be changed and it is hard to record the index in this algorithm.
Try to use dictionary:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
result_index = {}
for i in range(len(nums)):
target_1 = target - nums[i]
if target_1 not in result_index:
result_index[nums[i]] = i
else:
return sorted([i,result_index[target_1]])
Summary: try to use dictionary to record index.