1-Two Sum
来源:互联网 发布:学校网络运行管理制度 编辑:程序博客网 时间:2024/06/06 00:12
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
tags:
Array, Hash Table
Solution 1(Time Limit Exceeded)
暴力法,直接while条件游标循环搜出两个和为target的数,输出序号即可
代码:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> elements;
for (int i = 0; i < numbers.size(); i++) {
for(int j = i+1; j<numbers.size(); j++){
if((numbers[i] + numbers[j] == target) && (i != j)){
elements.push_back(i);
elements.push_back(j);
break;
}
}
}
return elements;
}
};
Solution 2(Accepted)
哈希表法,把数组中各数按值把序号赋给哈希表,然后循环数组中的数,计算target-当前数值所得的数在哈希表里查出是否有,有则break并给出当前数和查出第二个数的序号,没有则继续
代码:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
unordered_map<int, int> map;
vector<int> elements;
for (int i = 0; i < numbers.size(); i++) {
map[numbers[i]] = i;
}
for (int i = 0; i < numbers.size(); i++) {
int difference = target - numbers[i];
if (map.find(difference) != map.end() && map[difference] > i) {
elements.push_back(i + 1);
elements.push_back(map[difference] + 1);
break;
}
}
return elements;
}
};
Solution 3(Accepted)
排序夹逼法,先复制出一样的数组,排序,前序后序夹逼找出两个数,然后在原数组中查找序号
代码:
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> elements;
vector<int> nums = numbers;
std::sort(nums.begin(),nums.end());
int i = 0;
int j = nums.size() - 1;
while(i<j){
if(nums[i] + nums[j] == target){
for (int k = 0; k < numbers.size(); k++){
if(nums[i] == numbers[k]){
elements.push_back(k + 1);
}
else if(nums[j] == numbers[k]){
elements.push_back(k + 1);
}
if(elements.size() == 2){
break;
}
}
break;
}
else if(nums[i] + nums[j] < target){
i++;
}
else if(nums[i] + nums[j] > target){
j--;
}
}
return elements;
}
};
- LeetCode 1 - 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
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- 1 Two Sum
- Problem 1: Two Sum
- LeetCode | #1 Two Sum
- 1、Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- 1 Two Sum
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- 详解Java中的clone方法 -- 原型模式
- Gcc的内建函数 __builtin_constant_p
- Docker 在Ubuntu 14.04上的安装
- uvalive 4256(dp)
- Oracle 分析函数 row_number
- 1-Two Sum
- iOS CALayer自定义
- NFC笔记——NFCIP-1协议命令集(NFCIP-1 Protocol Command Set)
- Python笔记:shutil模块
- 连连看——网易游戏2016实习生招聘
- Atitit.获取验证码图片通过web
- 黑马程序员——javase基础--多线程
- JNDI配置数据源
- centOS下的jdk1.7.0_75安装