Given an array of integers, return indices of the two numbers such this they add to a specific target.
You may assume this each input would have exactly one solution.
Example:
Input: numbers={2, 7, one, target=9
Output: (0,1)
Topic Analysis:
Given an array of integers, arbitrarily enter a number, look in the array and return the position of the two digits that can be added to the number. Cannot sort, otherwise it will disturb the position within the original array, the title requirement is to find the original location.
method One:
Train of thought: Use double loop, get any combination of sum, judge whether and the number of input equal.
Disadvantage: The time complexity is too high for O (n²), operating speed greatly discounted. And when submitted because of the time complexity will prompt the unqualified advantage: The simplest idea code: (This code cannot be submitted successfully, reason ↑)
Class Solution:
def twosum (self, Nums, target): For
I in range (len (nums)):
A=nums[i] for
J in range (Len ( Nums):
if TARGET-A==NUMS[J]: return
i,j
t=solution ()
arr=[1,2,3,6]
jg=t.twosum (arr,4)
Print (JG)
Run Result: (0,2)
method Two: to solve the problem of time complexity, it is necessary to simplify the cycle, using only one cycle, after referring to someone else's code, found that the method is to create an empty dictionary, through the loop to add elements while looking for the added elements of whether there is a qualified result. Advantages: Time complexity is O (n), space complexity is O (n). Disadvantage: Difficult to understand. Code: (Successful submission)
Class Solution:
def twosum (self, Nums, target):
dict={} for
I in range (len (nums)):
X=nums[i]
if Target-x in Dict: Return
(dict[target-x],i)
dict[x]=i #此时确定了字典内的内容为dict {x:i} note the key here (in fact, order 123) Placed in the position of I, where X is placed in the elements of the array. So the dict[target-x on the previous line returns the position
t=solution ()
arr=[3,2,3]
jg=t.twosum (arr,6)
print (JG)
Summary: use method Two before you can pass. My first thought was too simple to take into account the problem of time complexity. In the future in the process of doing problems must consider the speed of the problem. There are many solutions on the internet, bubble sort, hash function and so on, have time to try to understand, the speed should be better than my stupid method. But I think it's better for me to understand both of these methods. And as a beginner should also be OK.