当前位置:网站首页>leetcode.1 --- 两数之和
leetcode.1 --- 两数之和
2022-06-13 03:40:00 【_End丶断弦】
暴力解法

直接2层for循环暴力搜索,时间复杂度为O(n^2)
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
for(int i = 0;i < n;i++)
{
for(int j = i+1;j < n;j++)
{
if(nums[i] + nums[j] == target) return {
i, j };
}
}
return {
};
}
};
使用哈希表
定义一个r = target - nums[i],看是否能在哈希表中找到该元素,存在就返回该元素和下标即可,否则就存到哈希表中。
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hash;
for(int i = 0;i < nums.size();i++)
{
int r = target - nums[i];
if(hash.count(r)) return {
hash[r],i};
hash[nums[i]] = i;
}
return {
};
}
};
时间复杂度:O(n)
空间复杂度:O(n)
边栏推荐
- Panel data set of rural cities and towns: per capita consumption and expenditure of prefecture level cities 2012-2019 & rural data of provinces 2013-2019
- Lambda终结操作查找与匹配anyMatch
- YoloV5-Face+TensorRT:基于WIN10+TensorRT8.2+VS2019得部署
- UnionPay commerce - merchant statistics service platform
- Use lodash to merge the values of the same fields in an array object
- GoFrame第四天
- Get to know druid IO real time OLAP data analysis storage system
- 在JDBC连接数据库时报错:Connection to 139.9.130.37:15400 refused.
- Lambda终结操作max&min
- Workflow of driver of spark kernel (stage division, task division, task scheduling)
猜你喜欢

Time complexity
![[test development] automatic test selenium (I)](/img/cd/b6dc4ac53b4f30f745ec0590ac384b.png)
[test development] automatic test selenium (I)

The latest summary of key topics of journal C in 2022 - topic scope, contribution method and journal introduction

在JDBC连接数据库时报错:Connection to 139.9.130.37:15400 refused.

Detailed explanation of MySQL storage process

【测试开发】自动化测试selenium篇(一)

To resolve project conflicts, first-class project managers do so
![[200 opencv routines by youcans] 201 Color space conversion of images](/img/99/36ba75cda08fd816dce83eaeea9e8d.png)
[200 opencv routines by youcans] 201 Color space conversion of images

机器人避障系统基础

19 MySQL database optimization methods
随机推荐
微信扫描二维码无法下载文件的解决办法
Fundamentals of robot obstacle avoidance system
Local simulation download file
Multithreaded chat room, server and client
Lambda终结操作max&min
Oracle built-in functions
大五人格学习记录
Byte stream & buffer stream
LVS four layer load balancing cluster (4) main methods of load balancing
Watering artifact based on Huawei cloud Internet of things (stm32+esp8266)
单片机:I2C通信协议讲解
【测试开发】自动化测试selenium(三)——unittest框架解析
[test development] automatic test selenium (I)
Lambda终结操作查找与匹配noneMatch
Display line number in MySQL query result
Doris' table creation and data division
Druid query
Part II. S3. intuitionistic fuzzy multi-attribute decision-making method when attribute weight is intuitionistic fuzzy number
单片机:EEPROM 多字节读写操作时序
Scala method and function notes