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. java CyclicBarrier的介绍和使用

    一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point).在涉及一组固定大小的线程的程序中,这些线程必须不时地互相等待,此时 CyclicBarri ...

  2. Java第2章笔记

    1.什么是变量:在程序运行过程中它的值是允许改变的量 2.java中常用的数据类型分为四类八种  第一类:整型   int(整数类型)     byte(字节类型)    short(短整形)     ...

  3. 科学技术库Numpy

    一.生成矩形操作 1)numpy获取的数据是以  “,”  为分割的数据结构,来生成矩阵 注意:skip_header=1 去掉行首,即说明行 ,Cao jin,,,python,-- ,张二毛,,, ...

  4. python学习 day2 (3月2日)

    .if if else 和 if elif else 的区别是: 前者 判断第一个 判断完第二个 之后还会执行else: 后者是只有满足条件(即都不符合if.elif里的条件时才会进入else) 不清 ...

  5. Servlet WebSocket的简易聊天室

    添加依赖 <!-- websocket --> <dependency> <groupId>javax.websocket</groupId> < ...

  6. eclipse中tomcat启动设置参数

      今天新接触一个项目,使用java+flex做的单机项目,由于模块太多,打成war后就有300M左右了.所以,启动的时候,比较慢,超过了e eclipse中默认的45s,当我进行修改启动事件后,有一 ...

  7. 容器,表格 ,div,元素可左右拖动,滚动 css

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&quo ...

  8. Mathtype批量修改公式

    (1)将模板中的公式直接打开 (2)将需要修改好的公式复制黏贴到模板中 (3)再复制黏贴出,即可 PS: (1)统一设置公式格式 (2)统一设置公式大小

  9. Jersey RESTful WebService框架学习(二)使用@PathParam

    @PathParamuri路径参数写在方法的参数中,获得请求路径参数.比如:@PathParam("username") String userName 前端请求: <!DO ...

  10. js 上传文件夹

    最近公司做工程项目,实现文件夹上传. 网上找了一天,发现网上很多代码都存在相似问题,最后终于找到了一个符合要求的项目. 工程如下: 这里对项目的文件传输功能做出分析,怎么实现文件夹上传的,如何进行文件 ...