当前位置:网站首页>Leetcode sum of two numbers
Leetcode sum of two numbers
2022-07-06 01:38:00 【East invincible is me】
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 .
You can assume that each input corresponds to only one answer . however , The same element in the array cannot be repeated in the answer .
You can return the answers in any order .
My answer
Example 1:
Input :nums = [2,7,11,15], target = 9
Output :[0,1]
explain : because nums[0] + nums[1] == 9 , return [0, 1] .
Example 2:
Input :nums = [3,2,4], target = 6
Output :[1,2]
Example 3:
Input :nums = [3,3], target = 6
Output :[0,1]
Tips :
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
There will only be one valid answer
Advanced : You can come up with a time complexity less than O(n2) The algorithm of ?
My answer :
class Solution:
def twoSum(self,nums,target):
list1=[]
for x in nums:
for y in nums:
if (x+y==target):
list1.append(nums.index(x))
list1.append(nums.index(y))
return list1
The function I wrote , By traversing the list directly , Find the number first , Then enter the value index. Time complexity O(n Fang )
Input example 1 , Get the results you want . But it can be seen that , Yes, there is bug Of . If you enter an instance 2, Will be output [0,0] But this is not the desired result . so , When it comes to testing , You need to know the internal logic of the code , Otherwise, the selected test case data , The test passed . But the actual code bug Not tested .
The following solution , It won't exist index Repetitive questions . But the time complexity is still On Fang
class Solution:
def twoSum(self,nums,target):
list1=[]
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
if (nums[i]+nums[j]==target):
return[i,j]
return []
Solution 2 of the answer :
Hashtable
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
return []
Python There is no hash in , A dictionary is equivalent to a hash .
But I don't understand it here ,hashtable It's an empty dictionary , How to follow enumerate(nums) Related ?
Turn lists into dictionaries and lists .
I can't understand this writing , Put it down first , See if you can understand it later .
边栏推荐
- Redis-列表
- 安装Redis
- Cadre du Paddle: aperçu du paddlelnp [bibliothèque de développement pour le traitement du langage naturel des rames volantes]
- Unreal browser plug-in
- Format code_ What does formatting code mean
- CocoaPods could not find compatible versions for pod 'Firebase/CoreOnly'
- ClickOnce 不支持请求执行级别“requireAdministrator”
- 剑指 Offer 38. 字符串的排列
- Paddle框架:PaddleNLP概述【飞桨自然语言处理开发库】
- Threedposetracker project resolution
猜你喜欢
[flask] official tutorial -part3: blog blueprint, project installability
dried food! Accelerating sparse neural network through hardware and software co design
C web page open WinForm exe
How to upgrade kubernetes in place
leetcode刷题_反转字符串中的元音字母
Basic operations of database and table ----- delete data table
Threedposetracker project resolution
Leetcode skimming questions_ Verify palindrome string II
Initialize MySQL database when docker container starts
2022年PMP项目管理考试敏捷知识点(8)
随机推荐
[ssrf-01] principle and utilization examples of server-side Request Forgery vulnerability
How to see the K-line chart of gold price trend?
How does Huawei enable debug and how to make an image port
ORA-00030
Remember that a version of @nestjs/typeorm^8.1.4 cannot be obtained Env option problem
General operation method of spot Silver
yii中console方法调用,yii console定时任务
Electrical data | IEEE118 (including wind and solar energy)
Redis-字符串类型
SPIR-V初窥
Paddle框架:PaddleNLP概述【飞桨自然语言处理开发库】
现货白银的一般操作方法
Comments on flowable source code (XXXV) timer activation process definition processor, process instance migration job processor
【SSRF-01】服务器端请求伪造漏洞原理及利用实例
Leetcode1961. Check whether the string is an array prefix
ClickOnce does not support request execution level 'requireAdministrator'
How to upgrade kubernetes in place
ORA-00030
Mongodb problem set
SPIR-V初窺