一道关于运用Hashtable的题目

来源:互联网 发布:中国网络菜市场2017 编辑:程序博客网 时间:2024/05/17 22:44

You are given an array of integers and a sum. Find all pairs of integers that equal that sum. Assume you have some sort of data structures that will be able to store the pairs. Write an algorithm to find all these pairs.

 

这道题好像和我博客里面的另一道题有冲突,不过这里我放另外一个扩展性问题就是:

如果是三个数字,而不是两个数字相加呢,或者是找出4个数字相加起来为target的值的,据说要用到DP(Dynamic Programming)

以下是大致思路,感觉还靠谱


input : a[], target
: for(int i = 0; i < a.length; i++)
: for(int j = 0; j < a.length; j++)
: {
:    sum = a[i] + a[j];
:    if(hashmap.find(target-sum))
:          The four number is a[i], a[j], and the the element with index 
from 
: hashmap.getKey(target-sum)
:    else

原创粉丝点击