[LeetCode] Two Sum III - Data structure Design
11280 단어 LeetCode
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) -> truefind(7) -> false
Well, the basic idea is simple: just store the added numbers in an internal data structure. 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 and not at the same "position"as num, then return true. After iterating over 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. Since there may be duplicate numbers, personally I think using an unordered_map is a nice choice. It uses num as key and its number of appearances as value. 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_map>
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_map<int, 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[num]++;
40 }
41
42 bool twoSum::find(int sum) {
43 for (auto nums : data) {
44 int num = nums.first;
45 int counts = nums.second;
46 int another = sum - num;
47 if ((another == num && counts > 1) || (another != num && data.find(another) != data.end()))
48 return true;
49 }
50 return false;
51 }
52
53 void twoSumTest(void) {
54 twoSum ts = twoSum();
55 ts.add(1);
56 ts.add(3);
57 ts.add(5);
58 printf("Computed: ");
59 for (int sum = 1; sum <= 10; sum++)
60 printf("%d, ", ts.find(sum));
61 printf("
");
62 printf("Expected: 0, 0, 0, 1, 0, 1, 0, 1, 0, 0.
");
63 }
64
65 int main(void) {
66 twoSumTest();
67 system("pause");
68 return 0;
69 }
If you run this code, you may obtain the following result (I run it in Microsoft Visual Studio Professional 2012).
Computed: 0, 0, 0, 1, 0, 1, 0, 1, 0, 0,
Expected: 0, 0, 0, 1, 0, 1, 0, 1, 0, 0.
Well, since I have not bought these extra problems, I can only obtain the problem description from the web. So I am not quite clear about the interface of the provided Solution class. I just try to implement my code and test it based on my understanding of the problem description. Moreover, I am unable to test my code on the online judge and so my code may go wrong. If you have access to these problems and feel like trying my solution, please tell me about the result. Thank you very much!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.