当前位置:网站首页>【 LeetCode 】 1. The sum of two Numbers
【 LeetCode 】 1. The sum of two Numbers
2022-07-29 15:03:00 【Crispy~】
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标.
你可以假设每种输入只会对应一个答案.但是,数组中同一个元素在答案里不能重复出现.
你可以按任意顺序返回答案.
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] ==
9 ,返回 [0, 1] .
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109 只会存在一个有效答案
进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗
题解
Use brute force traversal
//C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int len = nums.size();
for(int i=0;i<len-1;i++)
{
for(int j=i+1;j<len;j++)
{
if(nums[i]+nums[j]==target)
return {
i,j};
}
}
return {
};
}
};
使用哈希表,Quickly search if a corresponding value exists
//C++
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> mynums;
for(int i = 0;i<nums.size();i++)
{
auto iter = mynums.find(target-nums[i]);
if(iter != mynums.end())
{
return {
iter->second,i};
}
mynums[nums[i]] = i;
}
return {
};
}
};
边栏推荐
- ArcGIS Molder Builder模型构建器基本知识
- kubernetes中正strace etcd
- 基于SSM实现在线聊天系统
- 为什么 ThreadLocal 可以做到线程隔离?
- C语言 5:bool类型,关系表达式,逻辑表达式,分支语句,函数调用机制,break,continue,goto,return/exit跳转语句
- 兆骑科创海外高层次人才引进平台,企业项目对接,赛事活动路演
- 求教一下 现在最新版的flinkcdc能获取到oracle的ddl变更信息吗?
- 即刻体验 | 借助 CTS-D 进一步提升应用设备兼容性
- 【微服务】(十六)—— 分布式事务Seata
- 暴力递归到动态规划 02 (绝顶聪明的人的纸牌游戏)
猜你喜欢
随机推荐
力扣之顺序表
AVH部署实践 (一) | 在Arm虚拟硬件上部署飞桨模型
Map遍历 key-value 的4种方法
【Postman】Download and installation (novice graphic tutorial)
带你搞懂 Redis 中的两个策略
这 6 款在线 PDF 转换工具,得试试
Why does APP use the JSON protocol to interact with the server: serialization related knowledge
Numpy
换掉 UUID,更快、更安全!
《外太空的莫扎特》
正斜杠 “/” 与反斜杠 “\”辨析
Zhaoqi Technology creates a platform for overseas high-level talent introduction, corporate project docking, and event roadshows
Guangzhou Emergency Management Bureau released the top ten safety risks of hazardous chemicals in summer
极市直播丨严彬-Unicorn:走向目标跟踪的大一统(ECCV2022 Oral)
微服务实战|集中配置中心Config非对称加密与安全管理
arcpy脚本制作arcgis工具箱注意事项
APP为什么用JSON协议与服务端交互:序列化相关知识
The raised platform system based on JSP&Servlet implementation
图斑自上而下,自左而右顺序编码,按照权属单位代码分组,每组从1开始编码
Guangzhou fire: high temperature weather frequent fire fire safety should not be ignored









