Force deduction question 1
Someone is driving , Someone is looking at the sea , Some people can't write the first title
———————————————————————————————— Split line
Get to the point
The first question is Sum of two numbers
Given an array of integers nums And an integer target value target, Please find... In the array And is the target value target the Two Integers , And return their array subscripts .
You can assume that each input corresponds to only one answer . however , The same element in the array cannot be repeated in the answer .
From freshman year , I don't know much about arrays and pointers , So it's quite evasive to see arrays , also python Grammar is not finished yet , After reading a little, I wrote directly , Make a note of , Supervise yourself to study hard
Reading questions : Integer found , Returns the subscript
The first method , Write two for loop , One by one
python in for Recycling method :for i in The interval to traverse :
Use to range function :range( The starting position ( Do not write default is 0 ), End position )
len( Array name , To obtain the length of the )
:for i in range(len(nums)):
for j in range(len(nums):
if i != j and nums[i]+a[j]==target
return [i,j]
retuen [ ]
Write it like this , Time complexity is high
By the way, review the calculation of time complexity :
You can see the link https://blog.csdn.net/hhmy77/article/details/106750276 It's OK. Take a look , I don't understand
Optimize it :
The way it's written is , Every time I traverse , There must be i= j The situation of , We can eliminate this situation directly in the cycle , There is no need to judge again in the conditional statement
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i]+a[j]==target
return [i.j]
return []
The above two violent problem solving methods , Under the guidance of brother Shun , There are other solutions , I'll make it up when I learn
Double pointer : First, sort the numbers in the array from small to large ,i Indicates the subscript of the first number ,j Subscript indicating the penultimate number ,nums[i]+nums[j], Addition of two numbers , If it is equal to target, The subscript is returned , If it is greater than target,j-1, If it is less than target, be i+1, When i=j Stop traversal when .
Dictionaries :
map: