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. Cookie、Session详解

    讲解的很全面 https://www.cnblogs.com/andy-zhou/p/5360107.html

  2. Oracle DBA面试突击题

    一份ORACLE DBA面试题 一:SQL tuning 类 1:列举几种表连接方式 答: Oracle的多表连接算法有Nest Loop.Sort Merge和Hash Join三大类,每一类又可以 ...

  3. C语言 · 大数加法

    算法提高 大数加法   时间限制:1.0s   内存限制:256.0MB      问题描述 输入两个正整数a,b,输出a+b的值. 输入格式 两行,第一行a,第二行b.a和b的长度均小于1000位. ...

  4. 网络相关命令-netstat

    网络相关命令 netstat显示网络状态 usage: netstat [-vWeenNcCF] [<Af>] -r netstat {-V|--version|-h|--help} ne ...

  5. oozie调度中的重试和手工rerun一个workflow

    在oozie中有Bundle.Coordinator和Workflow三种类型的job,他们之间可以有以下包含关系. Bundle > Coordinator > Workflow. 1. ...

  6. 第二百六十一节,Tornado框架模板引擎本质

    Tornado框架模板引擎本质 只需要了解一下即可 本篇就来详细的剖析模板处理的整个过程. 上图是返回给用户一个html文件的整个流程,较之前的Demo多了绿色流线的步骤,其实就是把[self.wri ...

  7. c#方法生成mysql if方法(算工作日)

    public static string retunSQl(string s,string e){ return @"IF ( "+s+ ">" +e+ ...

  8. nginx php文件上传的大小配置问题

  9. hdu 1180:诡异的楼梯(BFS广搜)

    诡异的楼梯 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/65536 K (Java/Others)Total Subm ...

  10. Qualcomm Vuforia SDK背景

    参考视频:http://edu.csdn.net/course/detail/1467/23125?auto_start=1 一:概述 官网:www.vuforia.com 应用方向:产品交互.虚拟购 ...