LeetCode #1 Two Sum
2015-08-09 16:23
393 查看
题目原文
Given an array of integers, find two numbers such that they add up toa 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
题目的意思非常简单,给定一个数组和一个数(目标值),问数组中是否有两个数的和等于目标值,如果有,给出两个数的下标。题目中已经限制了每个输入有些仅有一个答案。
这就很简单了,用哈希表就可以了。
提交代码
vector<int> twoSum(vector<int> &numbers, int target) { int max = INT_MIN; int min = INT_MAX; for (int i=0;i<numbers.size();i++) { if(numbers[i] >= max) max = numbers[i]; if(numbers[i] <= min) min = numbers[i]; } vector<short> hashTable(max - min + 1,0); for (int i=0;i<numbers.size();i++) { hashTable[numbers[i]-min] += 1; } for (int i=0;i<numbers.size();i++) { int leftTarget = target - numbers[i]; if(leftTarget<=max && leftTarget>=min) { if ((hashTable[leftTarget-min]>0 && leftTarget != numbers[i])|| (leftTarget == numbers[i] && hashTable[leftTarget-min] > 1)) { vector<int> out; out.push_back(i+1); for (int j=0;j<numbers.size();j++) { if(i != j && numbers[j] == target - numbers[i]) { out.push_back(j+1); } } if(out[0] > out[1]) { swap(out[0],out[1]); } return out; } } } vector<int> out; return out; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解