-
Notifications
You must be signed in to change notification settings - Fork 27
/
170. Two Sum III - Data structure design.c
87 lines (72 loc) · 1.97 KB
/
170. Two Sum III - Data structure design.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
170. Two Sum III - Data structure design
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
*/
typedef struct {
int *p;
int sz;
int n;
} TwoSum;
/** Initialize your data structure here. */
TwoSum* twoSumCreate() {
TwoSum *obj = malloc(sizeof(TwoSum));
//assert(obj);
obj->sz = 100;
obj->p = malloc(obj->sz * sizeof(int));
//assert(obj->p);
obj->n = 0;
return obj;
}
/** Add the number to an internal data structure.. */
void twoSumAdd(TwoSum* obj, int number) {
if (obj->n == obj->sz) {
// enlarge the buffer
obj->sz *= 2;
obj->p = realloc(obj->p, obj->sz * sizeof(int));
//assert(obj->p);
}
obj->p[obj->n ++] = number; // keep the array sorted if there is a need.
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
bool twoSumFind(TwoSum* obj, int value) {
int i, j;
for (i = 0; i < obj->n - 1; i ++) {
for (j = i + 1; j < obj->n; j ++) {
if (obj->p[i] + obj->p[j] == value) return true;
}
}
return false;
}
void twoSumFree(TwoSum* obj) {
free(obj->p);
free(obj);
}
/**
* Your TwoSum struct will be instantiated and called as such:
* struct TwoSum* obj = twoSumCreate();
* twoSumAdd(obj, number);
* bool param_2 = twoSumFind(obj, value);
* twoSumFree(obj);
*/
/*
Difficulty:Easy
Total Accepted:28.4K
Total Submissions:116.1K
Companies LinkedIn
Related Topics Hash Table Design
Similar Questions
Two Sum
Unique Word Abbreviation
Two Sum IV - Input is a BST
*/