中级农民
- 积分
- 104
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-9-16
- 最后登录
- 1970-1-1
|
danielgao 发表于 2012-3-21 14:40 ![]()
只知道n^2的做法
输出一个数组里所有的和为0的三个数
如果能用额外空间的话,好像可以用hash table做:
====================================
1. use a double-loop to traverse the whole array, enumerate each possible pair of numbers, build up a hash table, use the sum values of the two numbers as the key, and the positions of the two numbers as the values. O(n^2) time, O(n) space
2. traverse the whole array once again, for each value, try to retrieve the positons from the hash table by the key of [current value minus by zero]... done! O(n)
total time complexity: O(n^2), w/ additional O(n) space.
====================================
similarily, sum two numbers into a certain value,
1. create a hash table, use each value of the numbers in the array as a key, then their positions as values. O(n) time w/ O(n) space
2. traverse the whole array once again, for each value, try to retrieve the positions from the hash table by the key of [certain value minus current value]... done. O(n) time
total: O(n) time w/ O(n) additional space..
======================================
|
|