【发布时间】:2017-01-21 03:21:11
【问题描述】:
我从 Google here 的编码视频中找到了这个 sn-p
bool HasPairWithSum(const vector<int> data, int sum){
unordered_set<int> comp; //complements
for(int value : data){
if(comp.find(value) != comp.end)
return true;
comp.add(sum - value);
}
return false;
}
检查这对元素是否存在于总和等于给定总和的数组中,
以下测试用例按视频中的说明工作,
- {1, 2, 3, 9} 给定总和 = 8
- {1, 2, 4, 4} 给定总和 = 8
1.但是,我仍然很困惑以下哪个是正确的
if(comp.find(value) != comp.end) // as in snippet or
if(comp.find(value) == comp.end) // this one
2.另外,这个算法如何适应,
- {1, 2, 4, 6} 给定总和 = 8
【问题讨论】: