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)是一种极为普遍的数据结构,树的每一个节点最多只有 ...
随机推荐
- 1062: [NOI2008]糖果雨 - BZOJ
题目链接:http://www.lydsy.com:808/JudgeOnline/problem.php?id=1062 神题一个,直接讲思路了(全都是看别人的) 首先我们把一个云用一个平面上的点( ...
- select框宽度与高度设置(实用版)
在IE中只能使用 font-size: 限制 select 的高度. 同时使用 width:200px 限制宽度 size="20" 表示最多显示20个选项,超过20的需要 ...
- 程序自动生成Dump文件
前言:通过drwtsn32.NTSD.CDB等调试工具生成Dump文件, drwtsn32存在的缺点虽然NTSD.CDB可以完全解决,但并不是所有的操作系统中都安装了NTSD.CDB等调试工具.了解了 ...
- linux Ubuntu12 设置root用户登录图形界面
Ubuntu 12.04默认是不允许root登录的,在登录窗口只能看到普通用户和访客登录.以普通身份登陆Ubuntu后我们需要做一些修改,普通用户登录后,修改系统配置文件需要切换到超级用户模式,在终端 ...
- Qt 二进制文件读写(使用“魔术数字”)
今天开始进入 Qt 的另一个部分:文件读写,也就是 IO.文件读写在很多应用程序中都是需要的.Qt 通过 QIODevice 提供了IO的抽象,这种设备(device)具有读写字节块的能力.常用的IO ...
- Android:Resources资源文件
Android Resoureces是res目录下的那些目录和文件,常用的有: res/drawable/ 存放图片资源,类型有: 相关使用: Android:res之shape制作圆角 Androi ...
- 93. Restore IP Addresses
题目: Given a string containing only digits, restore it by returning all possible valid IP address com ...
- Java命令行实用工具jps和jstat
在Linux或其他UNIX和类UNIX环境下,ps命令想必大家都不陌生,我相信也有不少同学写过 ps aux | grep java | grep -v grep | awk '{print $2}' ...
- 在Tomcat上配置CAS 自己的体验
演示环境 本文演示过程在同一个机器上的(也可以在三台实体机器或者三个的虚拟机上),环境如下: windows732位 JDK 1.6.0_18 Tomcat 6.0.29 CAS-server-3.4 ...
- poj 2531 Network Saboteur( dfs )
题目:http://poj.org/problem?id=2531 题意:一个矩阵,分成两个集合,求最大的 阻碍量 改的 一位大神的代码,比较简洁 #include<stdio.h> #i ...