2 sum problem
来源:互联网 发布:网络萨顶顶歌曲大全 编辑:程序博客网 时间:2024/04/30 15:43
<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 endend
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)); endend
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; endend
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!!!!
- 2Sum Problem
- 2 sum problem
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- Sum Problem
- Sum Problem
- sum problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- sum problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- Sum Problem
- 按位与、或、异或等运算方法
- [搜索] Solr (二) 配置文件
- 如何实现WinForms窗体隐藏
- 有理想的程序员必须知道的15件事
- 对 HTTP 304 的理解(转)
- 2 sum problem
- WinForms窗体移动
- WampServer修改MySQL密码的问题
- C#Windows 窗体设计-实现欢迎界面-显示About窗体-在托盘中写入应用程序图标
- C# List<T>使用方式
- SETUP命令处理
- AsyncSocket中tag参数的用处
- 我的新学期规划
- ASP.NET弹出对话框几种基本方法