当前位置:网站首页>leetcode. 1 --- sum of two numbers
leetcode. 1 --- sum of two numbers
2022-06-13 03:52:00 【_ End, broken chord】
Violence solution
direct 2 layer for Circular violence search , The time complexity is O(n^2)
The code is as follows :
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 {
};
}
};
Use hash table
Define a r = target - nums[i], See if you can find this element in the hash table , If it exists, return the element and subscript , Otherwise, it will be stored in the hash table .
The code is as follows :
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 {
};
}
};
Time complexity :O(n)
Spatial complexity :O(n)
边栏推荐
- 机器人避障系统基础
- 单片机串口通信原理和控制程序
- Line height equals height why not center
- 5G China unicom 直放站 网管协议 实时性要求
- Summary of meeting between president Ren and scientists and experts in system engineering
- footstep
- [test development] fundamentals of software testing
- try-catch finally执行顺序的例题
- LVS four layer load balancing cluster (5) LVS overview
- Mobile communication exercises
猜你喜欢
随机推荐
Getting started with Oracle
大疆无人机飞控系统的原理、组成及各传感器的作用
[Yugong series] June 2022 Net architecture class 081 API customization task of distributed middleware schedulemaster
19 MySQL database optimization methods
任总与系统工程领域科学家、专家会谈纪要
Local simulation download file
单片机:Modbus 多机通信程序设计
缓存读写--写
Lambda end operation reduce merge
Promise combined with await
Very simple installation and configuration of nodejs
机器人避障系统基础
Student management system
单片机:RS485 通信与 Modbus 协议
【测试开发】文件压缩项目实战
Lambda end operation collect
LVS four layer load balancing cluster (4) main methods of load balancing
Multithreaded chat room, server and client
Use of Oracle PL-SQL
[interview review] update from time to time for personal use