Skip to content

Commit 36a2d50

Browse files
add problem 18 and test function
1 parent 3c5f33f commit 36a2d50

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

C/1-50/18-4Sum.c

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/*
2+
* Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
3+
4+
* Note: The solution set must not contain duplicate quadruplets.
5+
6+
* For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
7+
8+
* A solution set is:
9+
* [
10+
[-1, 0, 0, 1],
11+
[-2, -1, 1, 2],
12+
[-2, 0, 0, 2]
13+
* ]
14+
* Created by supercoderx on 2017/8/9.
15+
*/
16+
#include <stdio.h>
17+
#include <stdlib.h>
18+
19+
int **fourSum(int *nums, int numsSize, int target, int *returnSize) {
20+
*returnSize = 0;
21+
if (numsSize < 4) {
22+
return NULL;
23+
}
24+
25+
int p, q, sum, tmp, counter = 0, **result = NULL, *item = NULL;
26+
27+
// 排序
28+
for (int m = 0; m < numsSize - 1; m++) {
29+
for (int n = 0; n < numsSize - 1 - m; n++) {
30+
if (nums[n] > nums[n + 1]) {
31+
tmp = nums[n];
32+
nums[n] = nums[n + 1];
33+
nums[n + 1] = tmp;
34+
}
35+
}
36+
}
37+
38+
// 挑序列
39+
for (int j = numsSize - 1; j > 2; j--) {
40+
for (int i = 0; i < j - 2; i++) {
41+
if (i > 0 && nums[i - 1] == nums[i] || j < numsSize - 1 && nums[j] == nums[j + 1]) {
42+
continue;
43+
}
44+
sum = target - nums[i] - nums[j];
45+
p = i + 1;
46+
q = j - 1;
47+
while (p < q) {
48+
if (nums[p] + nums[q] == sum) {
49+
item = malloc(sizeof(int) * 4);
50+
item[0] = nums[i];
51+
item[1] = nums[p];
52+
item[2] = nums[q];
53+
item[3] = nums[j];
54+
(*returnSize)++;
55+
if (result == NULL) {
56+
result = malloc(sizeof(int *));
57+
} else {
58+
result = realloc(result, sizeof(int *) * (*returnSize));
59+
}
60+
result[*returnSize - 1] = item;
61+
p++;
62+
q--;
63+
while (p < q && nums[p - 1] == nums[p]) p++;
64+
while (p < q && nums[q + 1] == nums[q]) q--;
65+
} else if (nums[p] + nums[q] < sum) {
66+
p++;
67+
} else {
68+
q--;
69+
}
70+
}
71+
}
72+
}
73+
return result;
74+
}
75+
76+
void testFourSum() {
77+
int a[] = {1, 0, -1, 0, -2, 2};
78+
int b[] = {-3, -1, 0, 2, 4, 5};
79+
int target = 0, count = 0;
80+
// int **result = fourSum(a, 6, target, &count);
81+
int **result = fourSum(b, 6, target, &count);
82+
for (int i = 0; i < count; i++) {
83+
printf("%d,%d,%d,%d\n", result[i][0], result[i][1], result[i][2], result[i][3]);
84+
}
85+
86+
}

0 commit comments

Comments
 (0)