LeetCode题解——Two Sum
题目地址:https://oj.leetcode.com/problems/two-sum/
Two Sum
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
题目大意:
给定一个数组,找出其中两个数,它们的和等于给定的值。
函数返回这两个数的“下标”,下标按序排列,从1开始计算。
每个输入有且只有一个解。
分析:
①暴力解法。
求每两个元素的和,时间为O(n2)。
②先排序,后查找 或者 左右夹逼。
排序时间O(n logn),由于需要记录下标和元素值的关系,空间复杂度O(n)。然后:
查找:对每一个元素a,二分查找target - a是否存在。总时间为O(n logn) + O(n logn) = O(n logn);
夹逼:利用一对首尾指针求和,和<target,则首指针右移;和>target,则尾指针左移;相等则返回记录的下标值。总时间为O(n logn) + O(n) = O(n logn)。
③利用哈希表查找。
哈希表记录元素对应下标,对于元素a,O(1)时间查找target - a是否存在。总时间为O(n)。
程序挂掉的几个测试用例:
[5, 75, 25] 100 //排序之后下标顺序问题
[3, 2, 4] 6 //3 + 3 == 2 + 4 同一个元素被计算两次
[0, 4, 3, 0] 0 //0 + 0 元素重复,哈希表覆盖
代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <tr1/unordered_map>
using namespace std;
using namespace tr1; //②先排序,再夹逼。用一个辅助struct来记录数据和下标信息,并自定义比较函数,来对struct数组排序。
struct node{
int data;
int index;
node(int _data, int _index): data(_data), index(_index)
{
}
}; bool myCmp(node n1, node n2)
{
return n1.data < n2.data;
} vector<int> twoSum1(const vector<int> &numbers, int target)
{
vector<int> result; if(numbers.empty())
{
return result;
} vector<node> nv; //space: O(N)
for(int i = ; i < numbers.size(); ++i) //time: O(N)
{
nv.push_back( node(numbers[i], i) );
} sort(nv.begin(), nv.end(), myCmp); //排序,time: O(NlgN) int hIdx = , tIdx = nv.size() - ; while(hIdx < tIdx) //夹逼,time: O(N)
{
int sum = nv[hIdx].data + nv[tIdx].data; if(sum == target)
{
result.push_back(min(nv[hIdx].index, nv[tIdx].index) + );//min、max来确保下标顺序
result.push_back(max(nv[hIdx].index, nv[tIdx].index) + );
break;
}
else if(sum < target)
{
++hIdx;
}
else
{
--tIdx;
}
} //while return result;
} //③哈希表,由数据映射到下标,相同数据只记录最后一个下标。
vector<int> twoSum2(const vector<int> &numbers, int target)
{
vector<int> result; if(numbers.empty())
{
return result;
} unordered_map<int, int> num2loc; //space: O(N)
for(int i = ; i < numbers.size(); ++i) //哈希映射,time: O(N)
{
num2loc[ numbers[i] ] = i;
} for(int i = ; i < numbers.size() - ; ++i) //查找,time: O(N)
{
int gap = target - numbers[i]; if( num2loc.find(gap) != num2loc.end() && num2loc[gap] > i )
{
result.push_back(i + );
result.push_back(num2loc[gap] + );
break;
}
} return result;
} int main()
{
int nums[] = {,,,};
vector<int> numbers(nums, nums + sizeof(nums)/sizeof(*nums));
int target = ; vector<int> result; result = twoSum1(numbers, target);
for(int i = ; i < result.size(); ++i)
{
cout << result[i] << ' ';
}
cout << endl; result = twoSum2(numbers, target);
for(int i = ; i < result.size(); ++i)
{
cout << result[i] << ' ';
}
cout << endl; return ;
}
LeetCode题解——Two Sum的更多相关文章
- [LeetCode 题解] Combination Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a se ...
- [LeetCode 题解]: Two Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given an a ...
- LeetCode题解之Sum Root to Leaf Numbers
1.题目描述 2.问题分析 记录所有路径上的值,然后转换为int求和. 3.代码 vector<string> s; int sumNumbers(TreeNode* root) { tr ...
- 回溯法 leetcode题解 Combination Sum 递归法
题目大意:给出一个数组,用这些数组里的元素去凑一个target.元素可以重复取用. 感觉对这种题目还是生疏的.脑子里有想法,但是不知道怎么表达出来. 先记录下自己的递归法.应该还可以用循环实现. 回溯 ...
- LeetCode题解之 Sum of Left Leaves
1.题目描述 2.问题分析 对于每个节点,如果其左子节点是叶子,则加上它的值,如果不是,递归,再对右子节点递归即可. 3.代码 int sumOfLeftLeaves(TreeNode* root) ...
- [LeetCode 题解]:Path Sum
前言 [LeetCode 题解]系列传送门: http://www.cnblogs.com/double-win/category/573499.html 1.题目描述 Given a bi ...
- [LeetCode] #167# Two Sum II : 数组/二分查找/双指针
一. 题目 1. Two Sum II Given an array of integers that is already sorted in ascending order, find two n ...
- [LeetCode] #1# Two Sum : 数组/哈希表/二分查找/双指针
一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of ...
- 【LeetCode题解】二叉树的遍历
我准备开始一个新系列[LeetCode题解],用来记录刷LeetCode题,顺便复习一下数据结构与算法. 1. 二叉树 二叉树(binary tree)是一种极为普遍的数据结构,树的每一个节点最多只有 ...
随机推荐
- bnuoj 29373 Key Logger(模拟双向队列)
http://www.bnuoj.com/bnuoj/problem_show.php?pid=29373 [题意]:模拟光标输入 [题解]:用双向列表模拟实现,这里用其他模拟会超时,注意内存的释放 ...
- 4.4 spring-自定义标签的解析
1.0 自定义标签的解析. 在之前的章节中,我们完成了对spring 默认标签的加载过程.那么现在我们将开始新的里程, spring 自定义标签的解析; 代码如下: /** * Parse the e ...
- ExtJS4.2学习(九)属性表格控件PropertyGrid(转)
鸣谢网址:http://www.shuyangyang.com.cn/jishuliangongfang/qianduanjishu/2013-11-15/178.html ------------- ...
- 17款免费的Bootstrap后台管理模板集合
Bootstrap是Twitter推出的一个用于前端开发的开源工具包.是目前最受欢迎的前端框架之一.下面为大家推荐17个免费的Bootstrap后台管理界面模板. 1. Admin Lite ...
- 《head first java 》读书笔记
Updated 2014/03/26 P300-P402 Updated 2014/03/25 P213-300 Updated 2014/03/20 P0-P213 对象本身已知的事物被称为: 实例 ...
- IDFA问题,苹果上传问题。improper Advertising identifier [IDFA] Usage.
原地址: 报告 improper Advertising identifier [IDFA] Usage. Your app contains the Advertising Identifier [ ...
- 单例模式Java“完美”实现
我们通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源.如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案. public cl ...
- 修改MYSQL数据库表的字符集
MySQL 乱码的根源是的 MySQL 字符集设置不当的问题,本文汇总了有关查看 MySQL 字符集的命令.包括查看 MySQL 数据库服务器字符集.查看 MySQL 数据库字符集,以及数据表和字段的 ...
- IText 生成简单表格(报表)doc文档 单元居中
IText生成doc文档需要三个包:iTextAsian.jar,iText-rtf-2.1.4.jar,iText-2.1.4.jar 亲测无误,代码如下所示: import com.lowagie ...
- linux后台执行命令&
当在前台运行某个作业时,终端被该作业占据:而在后台运行作业时,它不会占据终端.可以使用&命令把作业放到后台执行. 如:30 2 * * * /data/app/scripts/hotbacku ...