Home > other >  Challenge the free brush day one: Leetcode - the sum of two Numbers - python
Challenge the free brush day one: Leetcode - the sum of two Numbers - python

Time:09-19

1.
to the sum of two NumbersNums given an integer array and the target value of a target, can you please find out and in the array for the target values of the two integers, and return to their array subscript,
You can assume that each input only corresponding to an answer, however, cannot use the same element in an array twice,

Example:

A given nums=[2, 7, 11, 15], target=9
Because nums nums [0] + [1]=2 + 7=9
So back to [0, 1]

a, violence, use double deck for loop, check whether the two Numbers in the nums and is equal to the target.
Advantages: simple
The downside: time complexity O (n ^ 2)

 
# violence solve method
The class Solution (object) :
Def twoSum (self, nums, target) :
"" "
: type nums: List [int]
: type target: int
Rtype: List [int]
"" "
N=len (nums)
For x in range (n) :
For y in range (x + 1, n) :
If nums [x] + nums==[y] target:
Return the x, y
Break
The else:
The continue

2, steal a little lazy, use python's built-in functions, query target - nums [I] whether exists in nums array:
Benefits: reduce the time complexity O (n)
The downside: there are bosses more

 
# lazy method
The class Solution (object) :
Def twoSum (self, nums, target) :
"" "
: type nums: List [int]
: type target: int
Rtype: List [int]
"" "
N=len (nums)
For x in range (n) :
A=target - nums [x]
If a nums in:
Y=nums. Index (a)
If x==y: # need to judge whether the x and y equal
The continue
The else:
Return the x, y
Break
The else:
The continue



three, bosses processing method, use dict function, the nums in value as the key, the nums index as the value, the actual: want to use the dictionary fast query function, like using a hash table,
Benefits: reduce the time complexity O (n)
The downside: there are bosses more

 
# leetcode bosses method
The class Solution (object) :
Def twoSum (self, nums, target) :
"" "
: type nums: List [int]
: type target: int
Rtype: List [int]
"" "
N=len (nums)
For x in range (n) :
A=target - nums [x]
If a nums in:
Y=nums. Index (a)
If x==y: # need to judge whether the x and y equal
The continue
The else:
Return the x, y
Break
The else:
The continue
  • Related