博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Leetcode】1. Two Sum 集合中找到两个元素之和等于给定值
阅读量:6914 次
发布时间:2019-06-27

本文共 911 字,大约阅读时间需要 3 分钟。

1. 题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,

return [0, 1].

2. 思路

建立hashmap,去查找余数是否存在。

3. 代码

class Solution {public:    vector
twoSum(vector
& nums, int target) { vector
res; _map.clear(); int size = nums.size(); for (int i = 0; i < size; i++) { int cur = nums[i]; int need = target - cur; auto f = _map.find(need); if (f != _map.end()) { res.push_back(f->second + 1); res.push_back(i + 1); return res; } _map[cur] = i; } return res; }private: unordered_map
_map;};

转载地址:http://teicl.baihongyu.com/

你可能感兴趣的文章
MAVEN指南-4、pom.xml 文件详解
查看>>
我的友情链接
查看>>
Vue导入外部js文件或css文件
查看>>
迷茫的学,无措的期待
查看>>
linux常见系统故障排除
查看>>
后台启动 zookeeper 所有信息 输出到指定目录
查看>>
nuxt.js踩坑记录
查看>>
spark和hive集成
查看>>
Mysql一些维护命令
查看>>
瑞萨单片(R5F100LE)操作无线模块CC1100
查看>>
最好的emacs24配置及配色的修改
查看>>
GIS(四)——为js版搜狗地图添加边界+Marker和Brand的最终美化版
查看>>
AWS - VPC site-to-site ×××
查看>>
Spring Cloud Alibaba使用Sentinel限流_四
查看>>
Redisbook学习笔记(1)sds
查看>>
12.6-全栈Java笔记:Java网络编程(四)
查看>>
Django加载模板文件
查看>>
我的友情链接
查看>>
windowsserver2008取消显示关机原因
查看>>
axis2学习——axis2的安装
查看>>