您的位置:首页 > 职场人生

Careercup - Facebook面试题 - 5761467236220928

2014-05-02 07:16 309 查看
2014-05-02 07:06

题目链接

原题:

Given an array of randomly sorted integers and an integer k, write a function which returns boolean True if a pair of numbers exists in the array such that A[i] + A[j] = k and False otherwise. Provide an O(N) and an O(N log N) solution.


题目:给定一个未排序的数组,找出是否存在A[i] + A[j]等于某一个值。请给出一个O(n)的解法和一个O(n * log(n))的解法。

解法1:如果是O(n)解法的话,可以在扫描过程中逐渐向哈希表里添加数组元素,并同时查找target - A[i]是否存在于哈希表中。所谓的O(n)也是理想化的,条件是哈希过程中没有冲突。

代码:

// http://www.careercup.com/question?id=5761467236220928 #include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;

class Solution {
public:
bool findTwoSum(vector<int> &v, int target) {
int n = (int)v.size();
unordered_set<int> us;

if (n < 2) {
return false;
}

int i;
for (i = 0; i < n; ++i) {
if (us.find(target - v[i]) != us.end()) {
us.clear();
return true;
} else {
us.insert(v[i]);
}
}

us.clear();
return false;
};
};

int main()
{
int i;
int n;
vector<int> v;
int target;
Solution sol;

while (cin >> n && n > 0) {
v.resize(n);
for (i = 0; i < n; ++i) {
cin >> v[i];
}
cin >> target;
cout << (sol.findTwoSum(v, target) ? "True" : "False") << endl;
v.clear();
}

return 0;
}


解法2:可以通过先将数组排序,然后从两端向中间进行一次扫描。这个做法在Leetcode题集中的Two Sum已经提到了。排序过程是O(n * log(n))的,扫描则是O(n)的。

代码:

// http://www.careercup.com/question?id=5761467236220928 #include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;

class Solution {
public:
bool findTwoSum(vector<int> &v, int target) {
int n = (int)v.size();
unordered_set<int> us;

if (n < 2) {
return false;
}

int i;
for (i = 0; i < n; ++i) {
if (us.find(target - v[i]) != us.end()) {
us.clear();
return true;
} else {
us.insert(v[i]);
}
}

us.clear();
return false;
};
};

int main()
{
int i;
int n;
vector<int> v;
int target;
Solution sol;

while (cin >> n && n > 0) {
v.resize(n);
for (i = 0; i < n; ++i) {
cin >> v[i];
}
cin >> target;
cout << (sol.findTwoSum(v, target) ? "True" : "False") << endl;
v.clear();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: