[LeetCode]015-3Sum

本文解析了给定整数数组中寻找三个元素使它们的和等于零的问题,并提供了详细的解决方案。首先对数组进行排序,然后通过固定一个元素并搜索另外两个元素使其和等于目标值(即第一个元素的负值)的方法来解决该问题。为了去除重复的解,使用了特定的技术。最终的时间复杂度为O(n^2)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:
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:

Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)

Solution:
思路:
1、先排序,用STL自带Sort函数也行,自己写一个也行。
2、将3个数的sum转化成两个数的sum。很好理解,先确定一个数,再将两个数的和为另一个数的反面。
3、去重,vector有去相邻重复的办法。
4、复杂度为O(n^2)

 vector<vector<int>> threeSum(vector<int>& nums)
    {
        vector<vector<int>> result;
        vector<int> temp;

        int n = nums.size();
        int i,j,k,target,temp_value;

        if(n < 3)
            return result;
        QuickSort(nums,0,n-1);
        temp_value = nums[0];
        for(i=0;i<n;i++)
        {
            if(i && temp_value == nums[i])
                continue;
            target = -nums[i];
            j = i+1;
            k = n-1;
            while(j<k)
            {
                if(nums[j] + nums[k] == target)
                {
                    temp.push_back(nums[i]);
                    temp.push_back(nums[j]);
                    temp.push_back(nums[k]);
                    result.push_back(temp);
                    temp.clear();
                    j++;
                    k--;
                }
                else if(nums[j] + nums[k] > target)
                    k--;
                else 
                    j++;
             }
             temp_value = nums[i];
        }
        //vector<vector<int>>::iterator it = unique(result.begin(),result.end());
        //result.resize(distance(result.begin(),it));

        result.erase(unique(result.begin(),result.end()),result.end());
        return result;
    }

    void QuickSort(vector<int>& nums,int low,int high)
    {
        if(low >= high)
            return ;

        int first = low;
        int last = high;
        int pivot = nums[low]; //基准
        while(first<last)
        {
            while(nums[last] >= pivot && last>first)
            {
                last--;
            }
            nums[first] = nums[last];
            while(nums[first] < pivot && first < last)
            {
                first++;
            }
            nums[last] = nums[first];
        }
        nums[first] = pivot;
        QuickSort(nums,low,first-1);
        QuickSort(nums,first+1,high);

    }

这个博客讲解了kSum,4Sum,3Sum的问题。很全

http://tech-wonderland.net/blog/summary-of-ksum-problems.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值