版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hang404/article/details/84875441
题目描述:
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
题目解答:
方法1:排序法
在两数之和中,双指针求目标数的方法可以用在这里。外层遍历数组元素,将其相反数当作目标数,内层用双指针法确定是否存在目标数。需要注意的是重复元素的过滤,存储符合题意解之后,要跳过相等的数字,避免产生重复解。运行时间56ms左右,代码如下。
/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int comp(void* a, void* b) {
return *(int*)a > *(int*)b ? 1 : -1;
}
int** threeSum(int* nums, int numsSize, int* returnSize) {
int n = numsSize;
qsort(nums, n, sizeof(int), comp);
if(n < 3 || nums[0] > 0 || nums[0] + nums[1] + nums[2] > 0)
return NULL;
int** result = NULL;
int i = 0, size = 0;
int left = 0, right = 0;
for(i = 0; i < n - 2 && nums[i] <= 0; i++) {
left = i + 1;
right = n - 1;
while(left < right) {
if(nums[i] + nums[left] + nums[right] > 0)
right--;
else if(nums[i] + nums[left] + nums[right] < 0)
left++;
else {
size++;
result = (int**)realloc(result, size * sizeof(int*));
result[size - 1] = (int*)malloc(3 * sizeof(int));
result[size - 1][0] = nums[i];
result[size - 1][1] = nums[left];
result[size - 1][2] = nums[right];
while(left + 1 < n && nums[left] == nums[left + 1])
left++;
while(right - 1 >= 0 && nums[right] == nums[right - 1])
right--;
left++;
right--;
}
}
while(i + 1 < n && nums[i] == nums[i + 1])
i++;
}
*returnSize = size;
return result;
}
方法2: Hash+排序
排序完之后,将大于等于0的数字存入hash,直接申请最大正数max
加1的空间,出现过的数字标记为真,否则标记为假。接下来利用两层循环,在循环最内侧,利用hash查找符合条件的第三个数字是否存在,在找第三个数字时,符合以下判断条件即可存储:
target <= max && hash[target] && nums[j] < target
(最后一个条件保证存储的结果都是递增的,避免重复结果)target == nums[j] && flag
(flag表示nums[j]之前是否有与其相等的数字,有则为真,无则为假)
另外需要跳过第一层循环中重复元素。运行时间48ms,代码如下。
/**
* Return an array of arrays of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int comp(void* a, void* b) {
return *(int*)a > *(int*)b ? 1 : -1;
}
int** threeSum(int* nums, int numsSize, int* returnSize) {
int n = numsSize;
int i = 0, j = 0, size = 0, t = 0;
qsort(nums, n, sizeof(int), comp);
if(n < 3 || nums[0] > 0 || nums[n - 1] < 0 || nums[0] + nums[1] + nums[2] > 0)
return NULL;
bool* hash = (bool*)calloc(nums[n - 1] + 1, sizeof(bool));
for(i = 0; i < n; i++) {
if(nums[i] >= 0)
hash[nums[i]] = true;
}
int** result = NULL;
for(i = 0; i < n - 2 && nums[i] <= 0; i++) {
for(j = i + 1; j < n - 1; j++) {
bool flag = false;
while(nums[j] == nums[j + 1]) {
j++;
flag = true;
}
t = nums[i] + nums[j];
if(t > 0)
break;
if((-t <= nums[n - 1] && hash[-t] && nums[j] < -t) || (-t == nums[j] && flag)) {
size++;
result = (int**)realloc(result, size * sizeof(int*));
result[size - 1] = (int*)malloc(3 * sizeof(int));
result[size - 1][0] = nums[i];
result[size - 1][1] = nums[j];
result[size - 1][2] = -t;
}
}
while(nums[i] == nums[i + 1])
i++;
}
*returnSize = size;
return result;
}