Given a magic number sum, to find if there are two numbers whose sum equals to the number
2 posters
Page 1 of 1
Given a magic number sum, to find if there are two numbers whose sum equals to the number
Two solutions:
O(n): Traverse the array, put (array[i],sum-array[i]) into the hashtable, then traverse again, if array[i] in the hashtable, it means there are two numbers in the array.
O(1): 每store一个数n,就用n和每个已经存在数据结构中的数字想加求和,将这个和作为key
插入hashtable中,比如首先是empty,依次存入以下数,相对应的hashtable的key:
insert 2 -> ht: empty,
insert 3 -> ht: 5 (2+3)
insert 10 -> ht: 5, 12(2+10), 13(3+10)
insert 1 -> ht: 5, 12, 13, 3, 4, 11
insert 7 -> ht: 5, 12, 13, 3, 4, 11, 9, 10, 17, 8
。。。
more space but faster
O(n): Traverse the array, put (array[i],sum-array[i]) into the hashtable, then traverse again, if array[i] in the hashtable, it means there are two numbers in the array.
O(1): 每store一个数n,就用n和每个已经存在数据结构中的数字想加求和,将这个和作为key
插入hashtable中,比如首先是empty,依次存入以下数,相对应的hashtable的key:
insert 2 -> ht: empty,
insert 3 -> ht: 5 (2+3)
insert 10 -> ht: 5, 12(2+10), 13(3+10)
insert 1 -> ht: 5, 12, 13, 3, 4, 11
insert 7 -> ht: 5, 12, 13, 3, 4, 11, 9, 10, 17, 8
。。。
more space but faster
yangwenzhou- Posts : 5
Join date : 2011-09-23
Re: Given a magic number sum, to find if there are two numbers whose sum equals to the number
I have a question about second one.
The big O for O(1) is only the process of checking from the hashset, but for creating the hashset it still need O(n2).
Also I'm not sure how to print the pair of elements that added to sum from the second method.
The big O for O(1) is only the process of checking from the hashset, but for creating the hashset it still need O(n2).
Also I'm not sure how to print the pair of elements that added to sum from the second method.
yangwenzhou wrote:Two solutions:
O(n): Traverse the array, put (array[i],sum-array[i]) into the hashtable, then traverse again, if array[i] in the hashtable, it means there are two numbers in the array.
O(1): 每store一个数n,就用n和每个已经存在数据结构中的数字想加求和,将这个和作为key
插入hashtable中,比如首先是empty,依次存入以下数,相对应的hashtable的key:
insert 2 -> ht: empty,
insert 3 -> ht: 5 (2+3)
insert 10 -> ht: 5, 12(2+10), 13(3+10)
insert 1 -> ht: 5, 12, 13, 3, 4, 11
insert 7 -> ht: 5, 12, 13, 3, 4, 11, 9, 10, 17, 8
。。。
more space but faster
Similar topics
» print all subsets of an array whose sum equals one number
» you have an array of integers, find the longest subarray which consists of numbers that can be arranged in a sequence
» An array of integers, all appear twice except one, find this number.
» Find the number of inversions in an array
» Matrix find number of ways to reach the other corner
» you have an array of integers, find the longest subarray which consists of numbers that can be arranged in a sequence
» An array of integers, all appear twice except one, find this number.
» Find the number of inversions in an array
» Matrix find number of ways to reach the other corner
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|