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.

时间: 2024-10-23 06:15:13

TwoSum / Three Sum的相关文章

LeetCode_1 TwoSum

看书虽然有必要,但是光看书大家斗志到是没用的,但是没办法,科研项目和互联网没关,只能找点题目来刷了! 不多说,开始! LeetCode_1   TwoSum 题目说明: 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 tha

LeetCode --- 1. Two Sum

题目链接:Two Sum 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. Plea

Leecode -- TwoSum

question: 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

leetcode-1 Two Sum 找到数组中两数字和为指定和

 问题描述:在一个数组(无序)中快速找出两个数字,使得两个数字之和等于一个给定的值.假设数组中肯定存在至少一组满足要求. <剑指Offer>P214(有序数组) <编程之美>P176 Que:Given an array of integers, find twonumbers such that they add up to a specific target number. The function twoSum should return indices ofthe tw

170. Two Sum III - Data structure design

Design and implement a TwoSum class. It should support the following operations: add and find. add - Add the number to an internal data structure.find - Find if there exists any pair of numbers which sum is equal to the value. For example, add(1); ad

leetCode 1. Two Sum 数组

1. Two Sum Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + n

leetcode中第一题twosum问题解答算法的可行性证明

leetcode中第一题twosum问题解答算法的可行性证明 一.引入 关于leetcode中第一题twosum问题,网上已有不少高人做出过解答,并提出了切实可行的算法实现.我在解答该题时参考了博客http://www.zixue7.com/article-9576-1.html的解答.为让读者更直观地阅读和理解本文,先简要摘录以上博客的内容如下: 题目还原 Two Sum Given an array of integers, find two numbers such that they a

【LeetCode】167. Two Sum II - Input array is sorted

Two Sum II - Input array is sorted Given an array of integers that is already sorted in ascending order, 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 a

[LeetCode] #1# Two Sum : 数组/哈希表/二分查找

一. 题目 1. Two SumTotal Accepted: 241484 Total Submissions: 1005339 Difficulty: Easy Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solutio