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 ...
随机推荐
- DataTable xml 互相转换
//测试方法 public static DataTable Test() { string savePath = System.AppDomain.CurrentDomain.BaseDirecto ...
- socket的同步异步的性能差别,以及listen的参数backlog
先说listen的参数backlog,同步系统中分别设置为5,512,1024的跑分情况 跑分工具apache的ab,参数为:ab -n50000 -c300 backlog=5跑分结果 Reques ...
- 阿里云安骑士-Centos7系统基线合规检测-修复记录
执行命令 sysctl -w net.ipv4.conf.all.send_redirects=0sysctl -w net.ipv4.conf.default.send_redirects=0sys ...
- [转]MySQL索引原理及慢查询优化
MySQL凭借着出色的性能.低廉的成本.丰富的资源,已经成为绝大多数互联网公司的首选关系型数据库.虽然性能出色,但所谓“好马配好鞍”,如何能够更好的使用它,已经成为开发工程师的必修课,我们经常会从职位 ...
- linux挂载ntfs格式的硬盘
发生了一件辣眼睛的操作,一个现场应用升级,由于跨度很大,不敢直接动,就把现场的数据库dump拿回来,在公司做写升级测试. 于是,联系现场的工程师把数据库dump导出来,放到网盘弄回来. ------- ...
- 2019.01.21 NOIP训练 可持久化序列【模板】(可持久化treap)
传送门 题意简述:支持在把某个数插入到某版本的第k个位置,删除某版本第k个数,询问第k个数. 思路:用可持久化treaptreaptreap维护区间第kkk个位置的数是啥就可以了. 代码
- 2019.01.20 bzoj2238: Mst(kruskal+树链剖分)
传送门 树链剖分菜题. 题意简述:给一个无向图,边有边权,每次询问删一条边(对后面的询问无影响)之后的最小生成树. 思路: 先跑一次kruskalkruskalkruskal并把跑出来的最小生成树给链 ...
- bootstrap表格参数说明
表格参数: 名称 标签 类型 默认 描述 - data-toggle String ‘table’ 不用写 JavaScript 直接启用表格. classes data-classes String ...
- best-case analysis in real-time system
ECRTS: Exact Best-Case Response Time Analysis of Fixed Priority Scheduled Tasks motivation Real-time ...
- winform 可拖动无边框窗体解决办法
方法一:通过重载消息处理实现. 鼠标的拖动只对窗体本身有效,不能在窗体上的控件区域点击拖动 /// <summary> /// 通过重载消息处理实现.重写窗口过程(WndProc),处理一 ...