Redian新闻
>
Check if the sum of two integers in an integer array eqauls to the given number
avatar
Check if the sum of two integers in an integer array eqauls to the given number# Programming - 葵花宝典
z*e
1
I saw a similar post in this board, and recalled my recent interview
experience. Got this question in Amazon interview. Although I failed, it is
still a good one.
My answer:
1. Create a hash table to store all integers in this array. O(n)
2. For each int, look for sum - int in the created hash tree. Since hash
tree is the fastest look-up table, we can take advantage from it. n*O(1)
3. So this is O(n) algorithm.
Then the guy gave me the array 1, 2, 10, 20, sum is 2. My answer will return
true obv
avatar
o*r
2
What if you have a collision in setting up hash table.
Do you use list?
A simple solution is just count occurrence of a value.
Since it only needs to be checked when value == S/2,
the occurrence count doesn't affect much.

is
return

【在 z***e 的大作中提到】
: I saw a similar post in this board, and recalled my recent interview
: experience. Got this question in Amazon interview. Although I failed, it is
: still a good one.
: My answer:
: 1. Create a hash table to store all integers in this array. O(n)
: 2. For each int, look for sum - int in the created hash tree. Since hash
: tree is the fastest look-up table, we can take advantage from it. n*O(1)
: 3. So this is O(n) algorithm.
: Then the guy gave me the array 1, 2, 10, 20, sum is 2. My answer will return
: true obv

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。