-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy path15. 3Sum.c
98 lines (81 loc) · 2.39 KB
/
15. 3Sum.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
88
89
90
91
92
93
94
95
96
97
98
/*
15. 3Sum
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
*/
/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct res_s {
int **p;
int sz;
int n;
} res_t;
void add2res(res_t *res, int a, int b, int c) {
int *buff = malloc(3 * sizeof(int));
//assert(buff);
buff[0] = a;
buff[1] = b;
buff[2] = c;
if (res->sz == 0) {
res->sz = 10;
res->p = malloc(res->sz * sizeof(int **));
//assert(res->p);
} else if (res->sz == res->n) {
res->sz *= 2;
res->p = realloc(res->p, res->sz * sizeof(int **));
//assert(res->p);
}
res->p[res->n ++] = buff;
}
int cmp(const void *a, const void *b) {
return *(int *)a - *(int *)b;
}
int** threeSum(int* nums, int numsSize, int* returnSize) {
int i, x, y, k;
res_t res = { 0 };
qsort(nums, numsSize, sizeof(int), cmp);
for (i = 0; i < numsSize - 2; i ++) {
if (i != 0 && nums[i] == nums[i - 1]) continue;
x = i + 1;
y = numsSize - 1;
while (x < y) {
k = nums[i] + nums[x] + nums[y];
if (k == 0) {
// found one
add2res(&res, nums[i], nums[x], nums[y]);
x ++;
while (x < y && nums[x] == nums[x - 1]) x ++;
y --;
while (x < y && nums[y] == nums[y + 1]) y --;
} else if (k < 0) {
x ++;
while (x < y && nums[x] == nums[x - 1]) x ++;
} else {
y --;
while (x < y && nums[y] == nums[y + 1]) y --;
}
}
}
*returnSize = res.n;
return res.p;
}
/*
Difficulty:Medium
Total Accepted:231.6K
Total Submissions:1.1M
Companies Amazon Microsoft Bloomberg Facebook Adobe Works Applications
Related Topics Array Two Pointers
Similar Questions
Two Sum
3Sum Closest
4Sum
3Sum Smaller
*/