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

参见《编程之美》2.12快速寻找满足条件的两个数。这里采用的解法2中的hash表,采用C++中的map容器,以数组元素为key,因为要返回下标,以下标为value。算法时间复杂度O(n),空间复杂度O(n).

代码(AC):

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
map<int,int> map1;//<数值,下标>
vector<int> vin; int len = numbers.size();
//cout<<len<<endl;
for(int i = 0;i<len;i++)
{
map1[numbers[i]] = i;
}
for(int i = 0;i<len;i++)
{
int sum = target - numbers[i];
map<int,int>::iterator it = map1.end();
if(it != map1.find(sum)&&map1.find(sum)->second!=i)
{ vin.push_back(i+1);
vin.push_back(map1.find(sum)->second+1); }
}
return vin;
}
};

如果不要求返回符合条件元素在原数组的下标,《编程之美》中的解法三很巧妙。如果已经了这个数组任意两个元素之和的有序数组,那么采取Binary Search,在O(logN)时间内就可以解决问题。但是计算每两个元素和的有序数组需要O(n^2),我们并不需要求解这个数组。这个思考启发我们,可以直接对两个数字的和进行有序遍历,降低时间复杂度。

首选,对原数组进行排序,采用Qsort,时间复杂度O(NlogN);

声明两个下标,i = 0;j = n-1;比较array[i]+array[j]是否等于target,如果是返回array[i]和array[j],若小于target,则i++;如果大于target,则

j--;遍历一次即可。时间复杂度O(n).所以该方法的时间复杂度是O(n)+O(NlogN) = O(NlogN)。要是题目返回原始数组的下标,则在对原数组排序的时候要保存各个元素在原数组的下标。

伪代码:

Qsort(array);

for (i=0,j=n-1;i<j)

if(array[i]+array[j]==target) return (array[i],array[j]);

else if(array[i]+array[j]<target) i++;

else j--;

return ;







LeetCode_Two Sum的更多相关文章

  1. LeetCode - Two Sum

    Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...

  2. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  3. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  4. POJ 2739. Sum of Consecutive Prime Numbers

    Sum of Consecutive Prime Numbers Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20050 ...

  5. BZOJ 3944 Sum

    题目链接:Sum 嗯--不要在意--我发这篇博客只是为了保存一下杜教筛的板子的-- 你说你不会杜教筛?有一篇博客写的很好,看完应该就会了-- 这道题就是杜教筛板子题,也没什么好讲的-- 下面贴代码(不 ...

  6. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  7. [LeetCode] Partition Equal Subset Sum 相同子集和分割

    Given a non-empty array containing only positive integers, find if the array can be partitioned into ...

  8. [LeetCode] Split Array Largest Sum 分割数组的最大值

    Given an array which consists of non-negative integers and an integer m, you can split the array int ...

  9. [LeetCode] Sum of Left Leaves 左子叶之和

    Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two l ...

随机推荐

  1. Oracle 11g安装图文攻略

    一.Oracle 下载 注意Oracle分成两个文件,下载完后,将两个文件解压到同一目录下即可. 路径名称中,最好不要出现中文,也不要出现空格等不规则字符. 官方下地址: http://www.ora ...

  2. PyCharm 在django程序中单独运行py文件

    使用PyCharm开发django程序,发现如果不在命令行而在IDE的django项目中直接运行django程序,发现报错,程序如下:   def main(): from people.models ...

  3. CSS学习笔记(10)--nth-child和nth-of-type

    CSS3 :nth-child() 选择器 规定属于其父元素的第二个子元素的每个 p 的背景色: p:nth-child(2) CSS3 :nth-of-type() 选择器 规定属于其父元素的第二个 ...

  4. QTableWidget与QTableView的区别

    QTableWidget继承自QTableView.QSqlTableModel能与QTableView绑定,但不能于QTableWidget绑定 QSqlTableModel *model = ne ...

  5. MyBatis Geneator详解<转>

    MyBatis Geneator中文文档地址: http://generator.sturgeon.mopaas.com/ 该中文文档由于尽可能和原文内容一致,所以有些地方如果不熟悉,看中文版的文档的 ...

  6. ThinkPHP 的URL重写时遇到No input file specified的解决方法

    因为在Fastcgi模式下,php不支持rewrite的目标网址的PATH_INFO的解析 ThinkPHP运行在URL_MODEL=2时,会出现 No input file specified.的情 ...

  7. Python安装相关的机器学习库以及图像处理库

    安装 sudo apt-get install python-scipy sudo apt-get install python-numpy sudo apt-get install python-m ...

  8. 【BZOJ】1050: [HAOI2006]旅行comf(暴力+并查集)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1050 表示被暴力吓到了orz 我竟然想不到...我竟然还想到分数规划,,但是不可做...然后又想到最 ...

  9. 常用的jQuery前端技巧收集

    调试时巧用console.log(),这比用alert()方便多了. jquery易错点:元素拼接的时候,元素还未添加到DOM,就用该预添加元素操作. ajax动态获取的数据,还没有装载html元素, ...

  10. 怎么用ChemDraw连接两个结构片段

    作为最新版的ChemOffice 15.1的核心组件,ChemDraw几乎能解决所有平面化学结构中的绘制问题.如果用户想连接两个分开的结构片段,ChemDraw提供两种连接两个化学结构片段的方法,分别 ...