当前位置:网站首页>Force deduction question (1) -- sum of two numbers
Force deduction question (1) -- sum of two numbers
2022-07-28 09:16:00 【Metaphors of the world】
Sum of two numbers
Topic content
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 .
Example
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 ?
source : Power button (LeetCode)
link :https://leetcode.cn/problems/two-sum
Answer key
Answer 1 : Double cycle violent solution
The first reaction to this problem is the double loop solution .
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
for i in range(0, length):
for j in range(i+1, length): # Because there must be an answer , There is no need to consider the boundary problem of the second layer cycle , namely i+1 It must not equal length
if nums[i] + nums[j] == target:
return [i, j]
Obviously , Because it is a double cycle violent solution , So it takes a long time to pass on the buckle , Probably 3344 ms
Explanation 2 : Advanced version of double cycle solution
The first kind of double cycle of problem solving is the double cycle without brain , Don't judge whether it is necessary to double cycle —— For example, whether there is a number and the number of the first layer of the cycle add up to our target number .
So what we need to do in the advanced version is to add a layer of judgment before the second layer of circulation to judge whether it is necessary to carry out the second layer of circulation .
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
for i in range(0, length):
if (target - nums[i]) in nums: # Determine whether it is necessary to carry out the second layer of circulation
for j in range(i+1, length):
if nums[j] + nums[i] == target:
return [i, j]
The time of force buckle passing is about 728 ms
Answer 3 : utilize python function index
Direct search without double loop target - nums[i] The position of the number in the list
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(0, len(nums)):
num1 = target - nums[i]
if num1 in nums: # Judge target - nums[i] Is it in the list
j = nums.index(num1)
if j != i: # Judge whether the position of the positioned number is consistent with that of the first cycle
return [i, j]
The time of force buckle passing is about 724 ms
Solution 4 : Dictionary simulation hash table
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {
} # Dictionaries key Value record number ,value Record subscripts , Because there is only one answer , Don't consider the problem that the coverage caused by the same number leads to incomplete answers
for i in range(0, len(nums)):
num1 = target - nums[i]
if num1 in dic: # Determine whether the number exists in In the dictionary
return [dic.get(num1), i]
dic[nums[i]] = i # Record numbers and subscripts
The time of force buckle passing is about 40 ms
边栏推荐
- 01 tensorflow calculation model (I) - calculation diagram
- 站在大佬的肩膀上,你可以看的更远
- Kubernetes cluster configuration DNS Service
- Deconstruction assignment of ES6 variables
- Introduction of functions in C language (blood Book 20000 words!!!)
- Magic Bracelet-【群论】【Burnside引理】【矩阵快速幂】
- I use SqlClient normally, and dlink submission will report this error. What should I do?
- Post it notes -- 45 {packaging of the uniapp component picker, for data transmission and processing -- Based on the from custom packaging that will be released later}
- Feign调用异常[Running, pool size = 10, active threads = 10, queued tasks = 0, completed tasks = n]
- ES6 变量的解构赋值
猜你喜欢

Dry goods semantic web, Web3.0, Web3, metauniverse, these concepts are still confused? (top)

TXT文本文件存储

Network interface network crystal head RJ45, Poe interface definition line sequence

一款入门神器TensorFlowPlayground

What are the main uses of digital factory management system

VS2015使用dumpbin 查看库的导出函数符号

阿里云服务器搭建和宝塔面板连接

看得清比走得快更重要,因为走得对才能走得远

【SwinTransformer源码阅读二】Window Attention和Shifted Window Attention部分

Introduction of functions in C language (blood Book 20000 words!!!)
随机推荐
View the dimensions of the list
Hundreds of billions of it operation and maintenance market has come to the era of speaking by "effect"
ES6 let and Const
[592. Fraction addition and subtraction]
Will sqlserver CDC 2.2 generate table locks when extracting large tables from the source
Map of China province > City > level > District > Town > village 5-level linkage download [2019 and 2021]
App加速读取显示IPFS图片的解决方案和实现
DAPP safety summary and typical safety incident analysis
v-bind指令的详细介绍
Starfish Os打造的元宇宙生态,跟MetaBell的合作只是开始
TXT text file storage
Machine learning: self paced and fine tuning
【英语考研词汇训练营】Day 15 —— analyst,general,avoid,surveillance,compared
Feign调用异常[Running, pool size = 10, active threads = 10, queued tasks = 0, completed tasks = n]
蓝牙技术|2025年北京充电桩总规模达70万个,聊聊蓝牙与充电桩的不解之缘
The chess robot pinched the finger of a 7-year-old boy, and the pot of a software testing engineer? I smiled.
An entry artifact tensorflowplayground
快速上手Flask(一) 认识框架Flask、项目结构、开发环境
golang 协程的实现原理
(IROS 2022) 基于事件相机的单目视觉惯性里程计 / Event-based Monocular Visual Inertial Odometry