[leetcode] Two Sum
来源:互联网 发布:淘宝黑色半高领薄毛衣 编辑:程序博客网 时间:2024/06/11 00:48
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
A1 将数组按照关键值排序,从两端遍历寻找和为target的index:88ms
struct Node{ int value; int index; Node() {value=0; index=0;} Node(int v, int i):value(v), index(i) {}};bool compare(const Node &x, const Node &y){ return x.value<y.value;}class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<Node> nodes; for (int i=0; i<numbers.size(); i++) { nodes.push_back(Node(numbers[i],i+1)); } sort(nodes.begin(),nodes.end(),compare); int i = 0, j = nodes.size()-1; while (nodes[i].value + nodes[j].value != target) { if (nodes[i].value + nodes[j].value > target) j--; else i++; } vector<int> res; res.push_back(nodes[i].index<nodes[j].index?nodes[i].index:nodes[j].index); res.push_back(nodes[i].index>nodes[j].index?nodes[i].index:nodes[j].index); return res; }};
A2 建立哈希表,扫描一遍数列:92ms
class Solution {public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> res; map<int, vector<int>> number_map; for (int i=0; i<numbers.size(); i++) { if (number_map.count(target-numbers[i])) { res.push_back(number_map[target-numbers[i]][0]); res.push_back(i+1); return res; } number_map[numbers[i]].push_back(i+1); } }};
0 0
- 【Leetcode】Two Sum (Sum)
- LeetCode: Two Sum
- LeetCode: Two Sum
- [Leetcode] Two Sum
- LeetCode : Two Sum
- Leetcode: Two Sum
- leetcode 46: Two Sum
- [LeetCode] Two Sum
- LeetCode 1 - Two Sum
- Leetcode : Two Sum
- 【leetcode】Two Sum
- [LeetCode]Two Sum
- leetcode Two Sum
- [Leetcode] Two Sum
- [leetcode] Two Sum
- LeetCode - Two Sum
- leetcode之Two Sum
- LeetCode | Two Sum
- jitsi-android 项目 编译
- Teradata存储过程浅析
- 剑指offer:求字符的所有组合
- file open error: [Errno 2] No such file or directory: '\xe6\xb5\x8b\xe8\xaf\x95.txt'
- 实验五图像的拉普拉斯锐化
- [leetcode] Two Sum
- 正则表达式
- 电子设计省赛--DMA与ADC
- MySQL InnoDB的存储结构总结
- 剑指offer:八皇后问题
- 由C++的泛型句柄类思考OpenCV的Ptr模板类
- linux cd 命令的几个小技巧
- map,set----insert
- 开始使用Mac OS X——写给Mac新人