Let's begin with a naive method.

We first need to sort the array A[n]. And we want to solve the problem by iterating through A from beginning and ending. Then, if the sum is less than the target, we move the leading pointer to next right. When the sum is larger than target, we move the ending pointer to next left. The workflow of finding a, b such that $$a + b = target$$ as flows:

vector<vector<int> > res;

//we access the array from start point and end point
int* begin = A;
int* end = A + n - 1; while(begin < end){
if(begin + *end < target)//it means we need to increase the sum
begin += begin; if(begin + *end > target)//it means we need to decrease the sum
end -= end; if(begin + *end == target){
begin += begin;
end -= end;
res.push_back({*begin, *end}); // there may be some other combinations
++begin;
--end;
}
}

Running Time:

  • $O(n*\log{n})$ for sorting.
  • $O(n)$ for accessing through the array

In fact, there're some directly optimizations. When we move the pointer begin and end, it will stay the same status if $$ *(new\ begin) == *begin $$, or $$ *(new\ end) == *end$$. Thus, we can move the pointers until it reaches the first different value.

++begin;
while(begin < length && num[begin] == num[begin-1])
++begin;

and

--end;
while(end > 0 && num[end+1] == num[end])
--end;

Assume we have m same *begin, n same *end, we will reduce the running time of iterating moving points from $O(m*n)$ to $O(m+n)$.

Pay attention the above analysis and optimization are only useful when we find valid combination.

  • When $*begin + *end == target$. In this case, we need to move both begin and end. Thus we reduce running time from $O(m*n)$ to $O(m+n)$.
  • When $*begin + *end < target$, we only do m times ++begin. And when we get different begin, we stop. Without the optimization, the loop process is the same. So in this case, we only move the begin. The running time is always $O(m)$.
  • When $*begin + *end > target$, we have the same deduction. In this case, we only move end. The running time is always $O(n)$.

The Three Sum problem is based on the Two Sum problem above. In the Three Sum prolem, the direct optimization talked above is very important.

If we don't need to implement the three sum problem, we can use the hash table to get $O(n)$ running time.

TwoSum / Three Sum的更多相关文章

  1. LeetCode题解——Two Sum

    题目地址:https://oj.leetcode.com/problems/two-sum/ Two Sum Given an array of integers, find two numbers ...

  2. the sum of two fixed value

    the sum of two fixed value description Input an array and an integer, fina a pair of number in the a ...

  3. 【leetcode】633. Sum of Square Numbers(two-sum 变形)

    Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. ...

  4. LeetCode - Two Sum

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

  5. [LeetCode] Two Sum III - Data structure design 两数之和之三 - 数据结构设计

    Design and implement a TwoSum class. It should support the following operations:add and find. add - ...

  6. [LeetCode] Two Sum II - Input array is sorted 两数之和之二 - 输入数组有序

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  7. [LeetCode] Two Sum 两数之和

    Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...

  8. leecode系列--Two Sum

    学习这件事在任何时间都不能停下.准备坚持刷leecode来提高自己,也会把自己的解答过程记录下来,希望能进步. Two Sum Given an array of integers, return i ...

  9. LeedCode-Two Sum

    1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a ...

随机推荐

  1. 关于js的function.来自百度知道的回答,学习了.

    在js中,创建一个函数对象的语法是var myFunction = new Function(arg1,…,agrN, body);其中,该函数对象的N个参数放在 函数主体参数body的前面,即函数主 ...

  2. python之Flask框架

    一.简单的Flask框架 1)flask简介 Flask 是一个 web 框架.也就是说 Flask 为你提供工具,库和技术来允许你构建一个 web 应用程序. 这个 wdb 应用程序可以使一些 we ...

  3. 协程的NullReferenceException 错误

    public void loadPic(string url) { WWW www = new WWW(url); StartCoroutine(WaitForRequest(www)); } IEn ...

  4. centos7 sqoop 1 搭建笔记

    1.require : java环境,hadoop,hive ,mysql2.下载解压sqoop13.设置环境变量 export SQOOP_HOME=/data/spark/bin/sqoop ex ...

  5. 2018.12.31 NOIP训练 偶数个5(简单数论)

    传送门 对于出题人zxyoizxyoizxyoi先%\%%为敬题目需要龟速乘差评. 题意简述:5e55e55e5组数据,给出n,请你求出所有n位数中有偶数个5的有多少,n≤1e18n\le1e18n≤ ...

  6. 2018.11.02 NOIP模拟 距离(斜率优化dp)

    传送门 分四个方向分别讨论. 每次枚举当前行iii,然后对于第二维jjj用斜率优化dpdpdp. f[i][j]=(j−k)2+mindisk2f[i][j]=(j-k)^2+mindis_k^2f[ ...

  7. ubuntu卸载软件命令,apt-get remove

    第一步,apt-get remove xxx :就是卸载xxx  或者 apt-get remove --purge xxx :卸载xxx并清除配置.   这两条命令对于依赖则是不管的.因为别的软件可 ...

  8. ZOJ 3156 Taxi (二分 + 二分匹配)

    题意:给定 n 个人坐标, m 辆车的坐标,还有人的速度,要求每个人要进一辆不同的车,问你所有都进车的最短时间是多少. 析:首先二分时间 mid,很明显就是最后那个人进车的时间,然后如果把第 i 个人 ...

  9. python中的取整

    处理数据时,经常会遇到取整的问题,现总结如下 1,向下取整 int() >>>a = 3.1 >>>b = 3.7 >>>int(a) 3 > ...

  10. user表中存在多条相同user不同host用户信息时MySQL该匹配哪条记录登录?

    问题: 当用户名相同,但主机名不同的多条记录.用户由不同主机登录时,选择使用那条记录来验证,数据库版本为:5.6.25 如:IP为192.168.141.241 hostname为vhost02主机上 ...