minty_Brit666
Today’s blog is about the practice of the leetcode.
And I’ll give my own answer in this blog.
- The sum of two numbers
**Given an integer array nums and an integer target value target, find the two integers in the array and the target value target and return their array subscripts.
You can assume that there is only one answer for each type of input. However, the same element in the array cannot be repeated in the answer.
You can return the answers in any order.
Source: LeetCode
Link: https://leetcode-cn.com/problems/two-sum
Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
**
we can use the for loop twice to iterate through all the values and find the two numbers that sum to the target values:

def twoSum(self, nums, target):
n=len(nums)
for idx in range(n):
for jdx in range(idx+1,n):
if nums[idx] + nums[jdx] == target:
return idx,jdx
Or we can use the index to reduce a loop:

def twoSum(self, nums, target):
for idx in range(len(nums)):
if target - nums[idx] in nums:
if idx != nums.index(target - nums[idx]):
return idx,nums.index(target - nums[idx])
The easiest way to do that is to use a hash dictionary:

def twoSum(self, nums, target):
dict = {}
for idx in range(len(nums)):
x = target - nums[idx]
if x in dict:
return dict[x],idx
else:
dict[nums[idx]] = idx
Of the three methods above, the last one consumes the least amount of system resources and takes the least amount of time.
786

被折叠的 条评论
为什么被折叠?



