2 sum problem

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">Today I will introduce the classic 2 sum problem.</span>

Problem

Given a array of distinct numbers, write the a program to find if there exists a pair of number whose sum is X.

Variation

Given a array of distinct numbers, write the a program to find all pairs of number whose sum is X.


I will just give a simple description of the algorithm using matlab.


Version 1

N=10;
array = rand(1,N);
desired_sum=rand(1)+rand(1);
for i=1:N
    for j = 1:N
        if array(i)+array(j) == desired_sum
            fprintf('%d %d',array(i),array(j));
        end
    end
end


The complexity of the algorithm is O(n^2).


Version 2

N=10;
array = rand(1,N);
desired_sum=rand(1)+rand(1);
array=sort(array);
for i=1:N
    % binary_search here return 0 if it cannot find the element
    % or return the index of the element.
    [k]=binary_search(array,desired_sum-array(i));
    if k ~= 0
        fprintf('%d %d',array(i),array(k));
    end
end

The complexity of the algorithm is O(nlog(n)).

Version 3

N=5;
array = [1 2 7 3 6];
array=sort(array);
i = 1;
j = N;
x = 9;
while(i < j)
    if (array(i) + array(j) == x)
        fprintf('%d %d\n',array(i),array(j));
        i = i + 1;
        j= j - 1;
    end
    if array(i) + array(j) > x 
        j=j-1;
    end
    if array(i) + array(j) < x 
        i=i+1;
    end
end

This algorithm should take about half time of version 2. Let's demonstrate this algorithm really works. For every i, match j to check if they sum to x. if j is to big, j--. If the sum is less than x, we can assert that the we can stop the search for i. Let's search for i+1!!!!

Version 4

The last and the most efficient version is utilizing hashtable, which is a O(n) algorithm. However, it takes much more memory!!!!






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值