Given an array of integers, find the numbers such that they add up to a specific target number.
The function twosum should return indices of the numbers such that they add up to the target, where index1 must is Les S than Index2. Please note that your returned answers (both Index1 and INDEX2) is not zero-based.
You may assume this each input would has exactly one solution.
Input: numbers={2, 7, one, target=9
Output: index1=1, index2=2
classsolution (object):deftwosum (self, Nums, target):""": Type Nums:list[int]: type Target:int:rtype:list[int]""" #time:o (n) #space:o (n)Dict_num_index = {} forI, numinchEnumerate (nums): diff= Target-NumifDiffinchDict_num_index:return[Dict_num_index[diff], i + 1] " "if num not in dict_num_index:dict_num_index[num] = i + 1 #return the smallest I Ndex of the same value" "Dict_num_index[num]= i + 1
Time complexity: O (N)
Space complex: O (n)
Note: The string number can have duplicate values, and if you need to return the index with the smallest value, you need to write the code in the comments section
Leetcode:two Sum