Careercup - Facebook面试题 - 5761467236220928

时间:2023-03-09 03:37:08
Careercup - Facebook面试题 - 5761467236220928

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 < ) {
return false;
} int i;
for (i = ; 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 > ) {
v.resize(n);
for (i = ; i < n; ++i) {
cin >> v[i];
}
cin >> target;
cout << (sol.findTwoSum(v, target) ? "True" : "False") << endl;
v.clear();
} return ;
}

解法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 < ) {
return false;
} int i;
for (i = ; 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 > ) {
v.resize(n);
for (i = ; i < n; ++i) {
cin >> v[i];
}
cin >> target;
cout << (sol.findTwoSum(v, target) ? "True" : "False") << endl;
v.clear();
} return ;
}