Leetcode——1. Two Sum
来源:互联网 发布:淘宝正品代购是真的吗 编辑:程序博客网 时间:2024/06/10 05:01
题目
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].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
解答
用一个unordered_map的结构来存储numbers,其中key是nums中的元素,value是nums中该元素对应的下标。
由于unordered_map是基于hash表来实现的,所以其查找时间复杂度为O(1)。
但是先要存储,时间为O(N)。
hash.find(numberToFind) != hash.end()
如果成立,表明numberToFind是在hash里面。即找到了另外一个数字。
如果上面代码不成立,即numberToFind不在hash里面,所以需要加入。
经典代码:
**for (int i = 0; i < numbers.size(); i++) { int numberToFind = target - numbers[i]; //if numberToFind is found in map, return them if (hash.find(numberToFind) != hash.end()) { //+1 because indices are NOT zero based result.push_back(hash[numberToFind] + 1); result.push_back(i + 1); return result; } //number was not found. Put it in the map. hash[numbers[i]] = i;**
整个代码
vector<int> twoSum(vector<int> &numbers, int target){ //Key is the number and value is its index in the vector. unordered_map<int, int> hash; vector<int> result; for (int i = 0; i < numbers.size(); i++) { int numberToFind = target - numbers[i]; //if numberToFind is found in map, return them if (hash.find(numberToFind) != hash.end()) { //+1 because indices are NOT zero based result.push_back(hash[numberToFind] + 1); result.push_back(i + 1); return result; } //number was not found. Put it in the map. hash[numbers[i]] = i; } return result;}
0 0
- LeetCode — Two Sum
- LeetCode—Two Sum
- LeetCode—Two Sum
- leetcode—Two Sum
- LeetCode —-Two Sum
- LeetCode——1.Two Sum
- Leetcode——1. Two Sum
- LeetCode——1.Two SUM
- Leetcode——1. Two Sum
- LeetCode——1. Two Sum
- LeetCode——1. Two Sum
- 1. Two Sum——LeetCode OJ
- LeetCode——Two Sum
- LeetCode——Two Sum
- Leetcode —— Two Sum
- LeetCode——Two Sum
- Two Sum —— Leetcode
- LeetCode——Two Sum
- linux系统中设置oracle启停服务操作步骤
- 函数
- Sql执行顺序
- Collections类概述和常用成员方法
- HBase介绍
- Leetcode——1. Two Sum
- 查看mysql数据库 数据量大小和索引数据大小方法
- maven-compiler-plugin 插件版本信息错误提示的解决方法
- 这是what
- WPF复合控件
- JavaScript学习总结(一)基础部分
- android学习笔记(1)
- VS2010 连接 Oracle出现尝试加载 Oracle 客户端库时引发 BadImageFormatException 32位与64位问题解决方案
- day_01