当前位置:网站首页>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)
边栏推荐
- [200 Shengxin literatures] 95 multiomics exploration TNBC
- [unreal] key to open the door blueprint notes
- UE illusory engine programmed plant generator setup -- how to quickly generate large forests
- [ue5] animation redirection: how to import magic tower characters into the game
- Blender stone carving
- Junit4运行mvn test 测试套件升级方案
- What is the relationship between realizing page watermarking and mutationobserver?
- How much is it to develop a system software in Beijing, and what funds are needed to develop the software
- go语言入门
- Database -- acid of transaction -- introduction / explanation
猜你喜欢

Blender volume fog

ue4材质的入门和原理笔记

【UE5】AI随机漫游蓝图两种实现方法(角色蓝图、行为树)

Matlab代码生成之SIL/PIL测试

How to judge the quality of primary market projects when the market is depressed?

UE4夜间打光笔记

What wires are suitable for wiring on bread board?

MySQL transaction

Configuration programmée du générateur de plantes du moteur illusoire UE - - Comment générer rapidement une grande forêt

This article takes you to learn in detail what is fiber to home FTTH
随机推荐
UE5——AI追逐(藍圖、行為樹)
2837xd代码生成模块学习(1)——GPIO模块
Deep understanding of redis cache avalanche / cache breakdown / cache penetration
两数之和,求目标值
Junit5 supports suite methods
【虚幻】自动门蓝图笔记
C language strawberry
pytest学习--base
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
【JetBrain Rider】构建项目出现异常:未找到导入的项目“D:\VisualStudio2017\IDE\MSBuild\15.0\Bin\Roslyn\Microsoft.CSh
Pycaret | a few lines of code to solve machine learning modeling
Postman--使用
XA Transaction SQL Statements
渗透测试的介绍和防范
网络通信学习
Ctrip starts mixed office. How can small and medium-sized enterprises achieve mixed office?
UE4 night lighting notes
Mysql索引
Unreal material editor foundation - how to connect a basic material
Bookmark collection management software suspension reading and data migration between knowledge base and browser bookmarks