标签:
Problem Description:
Design and implement a TwoSum class. It should support the following operations: add and find.
add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
Well, the basic idea is simple: just store the added numbers in an internal data structure like vector, map or set. When we are asked to find a sum, we just iterate over all the numbers in the internal data structure. For each number num, if sum - num is also in the data structurue, then return true. After iterating all num and we have not returnred true, return false. The key to an efficient implementation lies in what data structure to store the added numbers. Personally I think using an unordered_set is a nice choice. It enalbes both O(1) insertion and O(1) query, and thus O(1) for add and O(n) for find if there are n elements in total.
Now comes the following code.
1 /** 2 Design and implement a TwoSum class. It should support the following operations: add and find. 3 4 add - Add the number to an internal data structure. 5 find - Find if there exists any pair of numbers which sum is equal to the value. 6 7 For example, 8 9 add(1); add(3); add(5); 10 find(4) -> true 11 find(7) -> false 12 */ 13 14 #include <iostream> 15 #include <unordered_set> 16 17 using namespace std; 18 19 class twoSum { 20 public: 21 twoSum(void); 22 ~twoSum(void); 23 24 void add(int); 25 bool find(int); 26 private: 27 unordered_set<int> data; 28 }; 29 30 twoSum::twoSum(void) { 31 data.clear(); 32 } 33 34 twoSum::~twoSum(void) { 35 data.clear(); 36 } 37 38 void twoSum::add(int num){ 39 data.insert(num); 40 } 41 42 bool twoSum::find(int sum) { 43 for (int num : data) { 44 int another = sum - num; 45 if (data.find(another) != data.end()) 46 return true; 47 } 48 return false; 49 } 50 51 void twoSumTest(void) { 52 twoSum ts = twoSum(); 53 ts.add(1); 54 ts.add(3); 55 ts.add(5); 56 printf("%d\n", ts.find(4)); 57 printf("%d\n", ts.find(7)); 58 }
Well, since I have not bought these extra problems, I can only obtain the problem description from the website. So I am not quite clear about the interface of the provided Solution class. And I am also unable to test my code on the online judge. If you have access to these problems and feel like trying my solution, please tell me about the result. Thank you very much!
[LeetCode] Two Sum III - Data structure Design
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4554395.html