Leetcode1
Given an array of integers and a target value, find the two numbers in the array and the target values.
You can assume that each input corresponds to only one answer, and that the same element cannot be reused.
Example:
Given nums = [2, 7, one, all], target = 9 because nums[0] + nums[1] = 2 + 7 = 9 so return [0, 1]
The idea at the beginning of this topic is to set two non-repeating pointers, which are returned when the number of two digits is the target value.
As follows:
Class solution (Object):
def twosum (self, Nums, target):
"""
: Type Nums:list[int]
: Type Target:int
: Rtype:list[int]
"""
N=len (Nums)
For I in range (n):
For j in Range (I+1,n):
If Nums[i]+nums[j]==target:
Return i,j
But this obvious readability is very high, easy to understand, the drawback is that time costs too much (N2)
The smaller the cost of the time, the greater the cost of space.
After watching someone else's code, get the following ideas:
With each value inside the Target-nums, save, O (n) space cost, see if the value exists in the original nuns, if present, then output these two values of index
The code is as follows:
ClassSolution(object):
DefTwosum(self, Nums, target):
"""
: Type Nums:list[int]
: Type Target:int
: Rtype:list[int]
"""
D = {}
ForI, numInchEnumerate (nums):
IfTarget-numInchD:
return [D[target-num], I]
D[num] = i
# for I, Num in enumerate (nums), called the Enumerate method, obtains a enumerate object, which can get the index and the object inside it with two parameters.
Leetcode Python 1 review