【力扣 - 三数之和】

题目描述

给你一个整数数组 nums ,判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != kj != k ,同时还满足 nums[i] + nums[j] + nums[k] == 0 。请你返回所有和为 0 且不重复的三元组。

注意:答案中不可以包含重复的三元组。

示例 1:

输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
解释:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0 。
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0 。
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0 。
不同的三元组是 [-1,0,1][-1,-1,2]
注意,输出的顺序和三元组的顺序并不重要。

示例 2:

输入:nums = [0,1,1]
输出:[]
解释:唯一可能的三元组和不为 0 。

示例 3:

输入:nums = [0,0,0]
输出:[[0,0,0]]
解释:唯一可能的三元组和为 0 。

提示:

3 <= nums.length <= 3000
-10^5 <= nums[i] <= 10^5

题解

快排 + 双指针法

2
​
,

在这里插入图片描述

代码

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
// Define a comparison function for qsort to sort integers in ascending order
int cmp(const void *a, const void *b)
{
    return *(int*)a - *(int*)b;
}

// Function to find all unique triplets that sum up to zero
int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
    *returnSize = 0; // Initialize the return size to 0
    if(numsSize < 3)
        return NULL; // If the input array has less than 3 elements, return NULL as no triplet can be formed

    qsort(nums, numsSize, sizeof(int), cmp); // Sort the input array in ascending order using the custom comparison function

    // Allocate memory for the 2D array to store the triplets and their sizes
    int **ans = (int **)malloc(sizeof(int *) * numsSize * numsSize);
    *returnColumnSizes = (int *)malloc(sizeof(int) * numsSize * numsSize);
    
    int i, j, k, sum;
    int indexLeft = 0;
    int indexMiddle = 0;
    int indexRight = 0;

    // Use three pointers to traverse the sorted array and find triplets that sum up to zero
    for (indexLeft = 0; indexLeft < numsSize - 2; indexLeft++)
    {
        if (nums[indexLeft] > 0) 
        {
            // If the current element is greater than 0, no triplet can sum up to zero, return the result
            /* if  nums[indexLeft]  is greater than 0, 
             * the function immediately returns  ans . 
             * In this case,  ans  will be returned without any modifications or additional calculations.  
             * The  ans  variable is a pointer to a 2D array of integers,
             * and at that point in the code, it would be returned as it is, 
             * without any triplets being calculated or added to it.
             */
            return ans;
        }
        
        // Skip duplicate values
        /* the keyword continue is used within a loop after a condition is met. 
         * When  continue  is encountered, 
         * it causes the program flow to immediately jump to the next iteration of the loop 
         * without executing the remaining code within the loop for the current iteration.
         * This helps in avoiding processing duplicate elements and 
         * ensures that only unique elements are considered during the loop execution. 
         */
        if (indexLeft > 0 && nums[indexLeft] == nums[indexLeft - 1])
            continue;

        indexMiddle = indexLeft + 1;
        indexRight = numsSize - 1;

        // Use two pointers to find all possible triplets
        while (indexMiddle < indexRight)
        {
            sum = nums[indexLeft] + nums[indexMiddle] + nums[indexRight];
            if (sum == 0)
            {
                // If the sum is zero, store the triplet in the ans array
                ans[*returnSize] = (int*)malloc(sizeof(int) * 3);
                (*returnColumnSizes)[*returnSize] = 3;
                ans[*returnSize][0] = nums[indexLeft];
                ans[*returnSize][1] = nums[indexMiddle];
                ans[*returnSize][2] = nums[indexRight];
                *returnSize += 1;

                // Skip duplicate values
                // This step is crucial to avoid considering the same combination of elements multiple times and ensures that only unique triplets are recorded. 
                while (indexMiddle < indexRight && nums[indexMiddle] == nums[++indexMiddle]);
                while (indexMiddle < indexRight && nums[indexRight] == nums[--indexRight]);
            }
            else if (sum > 0)
            {
                // If the sum is greater than zero, decrement the right pointer
                indexRight--;
            }
            else
            {
                // If the sum is less than zero, increment the middle pointer
                indexMiddle++;
            }
        }
    }
    return ans; // Return the 2D array containing the unique triplets
}

作者:我自横刀向天笑
链接:https://leetcode.cn/problems/3sum/solutions/1211127/san-shu-zhi-he-cyu-yan-xiang-jie-chao-ji-08q2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 11
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六月悉茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值