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)也是理想化的,条件是哈希过程中没有冲突。

代码:

 1 // http://www.careercup.com/question?id=5761467236220928
 2 #include <iostream>
 3 #include <unordered_set>
 4 #include <vector>
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     bool findTwoSum(vector<int> &v, int target) {
10         int n = (int)v.size();
11         unordered_set<int> us;
12         
13         if (n < 2) {
14             return false;
15         }        
16         
17         int i;
18         for (i = 0; i < n; ++i) {
19             if (us.find(target - v[i]) != us.end()) {
20                 us.clear();
21                 return true;
22             } else {
23                 us.insert(v[i]);
24             }
25         }
26         
27         us.clear();
28         return false;
29     };
30 };
31 
32 int main()
33 {
34     int i;
35     int n;
36     vector<int> v;
37     int target;
38     Solution sol;
39     
40     while (cin >> n && n > 0) {
41         v.resize(n);
42         for (i = 0; i < n; ++i) {
43             cin >> v[i];
44         }
45         cin >> target;
46         cout << (sol.findTwoSum(v, target) ? "True" : "False") << endl;
47         v.clear();
48     }
49     
50     return 0;
51 }

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

代码:

 1 // http://www.careercup.com/question?id=5761467236220928
 2 #include <iostream>
 3 #include <unordered_set>
 4 #include <vector>
 5 using namespace std;
 6 
 7 class Solution {
 8 public:
 9     bool findTwoSum(vector<int> &v, int target) {
10         int n = (int)v.size();
11         unordered_set<int> us;
12         
13         if (n < 2) {
14             return false;
15         }        
16         
17         int i;
18         for (i = 0; i < n; ++i) {
19             if (us.find(target - v[i]) != us.end()) {
20                 us.clear();
21                 return true;
22             } else {
23                 us.insert(v[i]);
24             }
25         }
26         
27         us.clear();
28         return false;
29     };
30 };
31 
32 int main()
33 {
34     int i;
35     int n;
36     vector<int> v;
37     int target;
38     Solution sol;
39     
40     while (cin >> n && n > 0) {
41         v.resize(n);
42         for (i = 0; i < n; ++i) {
43             cin >> v[i];
44         }
45         cin >> target;
46         cout << (sol.findTwoSum(v, target) ? "True" : "False") << endl;
47         v.clear();
48     }
49     
50     return 0;
51 }

 

 posted on 2014-05-02 07:16  zhuli19901106  阅读(235)  评论(0编辑  收藏  举报