当前位置:网站首页>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)
边栏推荐
- About the college entrance examination
- UE5——AI追逐(藍圖、行為樹)
- Bookmark collection management software suspension reading and data migration between knowledge base and browser bookmarks
- Nonlinear optimization: steepest descent method, Newton method, Gauss Newton method, Levenberg Marquardt method
- Application of rxjs operator withlatestfrom in Spartacus UI of SAP e-commerce cloud
- XA Transaction SQL Statements
- Zlib download and use
- Message mechanism -- getting to know messages and message queues for the first time
- MySQL -- time zone / connector / driver type
- Nonlinear optimization: establishment of slam model
猜你喜欢
![[ue5] blueprint making simple mine tutorial](/img/87/d0bec747a6b6276d63a315f88745ec.png)
[ue5] blueprint making simple mine tutorial

Illusion -- Animation blueprint, state machine production, character walking, running and jumping action
![[Yu Yue education] University Physics (Electromagnetics) reference materials of Taizhou College of science and technology, Nanjing University of Technology](/img/a9/ffd5d8000fc811f958622901bf408d.png)
[Yu Yue education] University Physics (Electromagnetics) reference materials of Taizhou College of science and technology, Nanjing University of Technology

Introduction et prévention des essais de pénétration

ue虚幻引擎程序化植物生成器设置——如何快速生成大片森林

Leetcode -- the nearest common ancestor of 236 binary tree

Alibaba cloud Prometheus monitoring service

Blender体积雾

Blender多鏡頭(多機比特)切換

Blender海洋制作
随机推荐
【虚幻4】从U3D到UE4的转型之路
【教程】如何让VisualStudio的HelpViewer帮助文档独立运行
Junit4运行mvn test 测试套件升级方案
Blender camera surround motion, animation rendering, video synthesis
Mobile mall app solution: how much is it to make an app? Detailed explanation of APP mall development content
【虚幻】按键开门蓝图笔记
Blender stone carving
Career planning and development
MySQL index
【虚幻4】UMG组件的简介与使用(更新中...)
Project practice, redis cluster technology learning (12)
XA Transaction SQL Statements
ESLint 报错
两数之和,求目标值
[illusory] automatic door blueprint notes
The latest progress and development trend of 2022 intelligent voice technology
Ctrip starts mixed office. How can small and medium-sized enterprises achieve mixed office?
[ue5] blueprint making simple mine tutorial
【Visual Studio】每次打开一个Unity3D的脚本,都会自动重新打开一个新的VS2017
Operator exercises