当前位置:网站首页>Sum the two numbers to find the target value
Sum the two numbers to find the target value
2022-07-02 10:21:00 【Lost ~ know to return】
Sum the two numbers to find the target value
subject : 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 .
Their thinking
Find the sum of two numbers , Using fast and slow pointers , When two pointers When the extracted function value is added to the target value , Meet the conditions
The first solution : Violence enumeration
This solution is the easiest to come up with , But the memory consumption is too large
class Solution(object):
def twoSum(self, nums, target):
""" :type nums: List[int] :type target: int :rtype: List[int] """
L = []
n = len(nums)
for i in range(n-1):
for j in range(i+1, n):
if nums[i] + nums[j] == target:
L.append(i)
L.append(j)
j = j + 1
i = i + 1
return L
double for loop : Double pointers for convenient summation
Time complexity :n*n, Spatial complexity , Introduced a new array , by n
Code transformation
class Solution(object):
def twoSum(self, nums, target):
# Method 1. Convenient array , Enumeration , Time and space consumption is huge
n = len(nums)
for i in range(n):
for j in range(i+1, n):
if nums[i] + nums[j] == target:
return [i, j]
return []
Time complexity :n*n, Spatial complexity :1
Method 2 : Hashtable
Function method :
The method of all key value pairs in the convenience dictionary :
for...in... # Loop statements to facilitate all key value pairs
==enumerate()== Function instructions :
- enumerate() yes python Built in functions for
- enumerate In the dictionary is enumeration 、 List means
- For an iterative (iterable)/ Traversable objects ( As listing 、 character string ),enumerate Make it into an index sequence , Use it to get both index and value
- enumerate It's mostly used in for Count in the loop
# for example : Output the subscript corresponding to each character in the list
listx = [" this ", " yes ", " One ", " test "]
for i in range(len(listx)):
print i, listx[i]
# enumerate() Use of functions
listx = [" this ", " yes ", " One ", " test "]
for index, item in enumerate(listx):
print index, item
The output is as follows :
Therefore, this question can be modified by hash table :
Thought analysis :
The time of searching in the list can be reduced through hash table
class Solution(object):
def twoSum(self, nums, target):
# Method 2 : Hashtable ,set No, index,dict No, add attribute
visited = dict()
for i,num in enumerate(nums):
if (target-num) in visited:
return (visited[target-num], i)
visited[nums[i]] = i
return []
error analysis :
- Use set, however set() Cannot return subscript , Therefore adopt dict()
Time complexity :o(N), Spatial complexity o(1)
边栏推荐
猜你喜欢
The latest progress and development trend of 2022 intelligent voice technology
How to judge the quality of primary market projects when the market is depressed?
It is the most difficult to teach AI to play iron fist frame by frame. Now arcade game lovers have something
阿里云Prometheus监控服务
[illusory] weapon slot: pick up weapons
Alibaba cloud SMS service
This monitoring system makes workers tremble: turnover intention and fishing can be monitored. After the dispute, the product page has 404
Following nym, the new project Galaxy token announced by coinlist is gal
Skywalking理论与实践
【Unity3D】嵌套使用Layout Group制作拥有动态子物体高度的Scroll View
随机推荐
pytest框架实现前后置
The latest progress and development trend of 2022 intelligent voice technology
Ue5 - AI pursuit (blueprint, behavior tree)
Summary of demand R & D process nodes and key outputs
Pycaret | a few lines of code to solve machine learning modeling
【避坑指南】Unity3D项目接入腾讯Bugly工具时遇到的坑
Alibaba cloud ack introduction
Postman--使用
2021-10-02
webUI自动化学习
Remember a simple Oracle offline data migration to tidb process
Deep understanding of redis cache avalanche / cache breakdown / cache penetration
Nonlinear optimization: establishment of slam model
Edge computing accelerates live video scenes: clearer, smoother, and more real-time
Nonlinear optimization: steepest descent method, Newton method, Gauss Newton method, Levenberg Marquardt method
ue虛幻引擎程序化植物生成器設置——如何快速生成大片森林
【UE5】动画重定向:如何将幻塔人物导入进游戏玩耍
阿里云Prometheus监控服务
Eslint reports an error
Following nym, the new project Galaxy token announced by coinlist is gal