TwoSum / Three Sum
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的更多相关文章
- LeetCode题解——Two Sum
题目地址:https://oj.leetcode.com/problems/two-sum/ Two Sum Given an array of integers, find two numbers ...
- 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 ...
- 【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. ...
- LeetCode - Two Sum
Two Sum 題目連結 官網題目說明: 解法: 從給定的一組值內找出第一組兩數相加剛好等於給定的目標值,暴力解很簡單(只會這樣= =),兩個迴圈,只要找到相加的值就跳出. /// <summa ...
- [LeetCode] Two Sum III - Data structure design 两数之和之三 - 数据结构设计
Design and implement a TwoSum class. It should support the following operations:add and find. add - ...
- [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 ...
- [LeetCode] Two Sum 两数之和
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- leecode系列--Two Sum
学习这件事在任何时间都不能停下.准备坚持刷leecode来提高自己,也会把自己的解答过程记录下来,希望能进步. Two Sum Given an array of integers, return i ...
- LeedCode-Two Sum
1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a ...
随机推荐
- g2o相关问题cs.h,以及no matching function for call to ‘g2o::OptimizationAlgorithmLevenberg::OptimizationAlgorithmLevenberg(Block*&)
1.对于cs.h找不到的情况 1)编译的时候一定要把csparse在EXTERNAL文件中,编译进去. 2)修改CMakeLists.txt文件中的include_directories中的${CPA ...
- mysql.lib 的使用
一 说明 mysql.lib 提供了很多方便的操作,同时结合 vector 使用十分方便. 二 使用 1 声明需要用到的变量 static MYSQL s_mysql[DATABASE ...
- ubuntu 配置ftp server(zz)
ubuntu 配置 ftp server 安装vsftpd sudo apt-get install vsftpd # vsftp(Very Secure FTP)是一种在Unix/Linux中非 ...
- Homebrew -- mac 缺失包补充工具
https://brew.sh/index_zh-cn.htmlhttps://brew.sh/ 非root权限下运行 # github 源代码 https://github.com/Homebrew ...
- IDEA的GUI连接数据库写入SQL语句的问题总结
一.首先是建立游标的对象statement 插入数据excuteUpdate需要的是一个整型的参数,所以建立的对象要是一个int型的数据类型,才可以执行SQL语句excuteQuery是一个字符类型在 ...
- 一道区间DP的水题 -- luogu P2858 [USACO06FEB]奶牛零食Treats for the Cows
https://www.luogu.org/problemnew/show/P2858 方程很好想,关键我多枚举了一次(不过也没多大关系) #include <bits/stdc++.h> ...
- decode 横竖转换
select rq 日期,sum(decode(shengfu,'胜',1,'负',0)) 胜,sum(decode(shengfu,'负',1,'胜',0)) 负 from tmp group by ...
- 【转】Linux修改SSH端口和禁止Root远程登陆
Linux修改ssh端口22 vi /etc/ssh/ssh_config vi /etc/ssh/sshd_config 然后修改为port 8888 以root身份service sshd res ...
- Java基本数据类型与包装类、字符串之间的转换
基本数据类型和包装类的转换:1.装箱:基本数据类型→对应包装类,可分为手动装箱和自动装箱.2.拆箱:包装类→对应基本数据类型,可分为手动拆箱和自动拆箱. 例子:手动装箱:Integer iObj=ne ...
- matlab 设定坐标比例
figure() u=-0.1:0.005:0.1; v=-0.1:0.005:0.1; [x,y]=meshgrid(u,v); z=sin(x-y)./abs(x)+abs(y); surf(x, ...