LeetCode算法题——15. 3Sum

题目:
Given an array S of n integers, are there elements abc 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]
]    

算法思想:
可以采用三层for直接搜索结果,此时算法复杂度为O(n^3),出现超时的错误,此时先对原始数据进行排序,先固定一个数,然后将3Sum可转换为2Sum问题,即寻找数组中满足两个数之和为target=0-第一个数的值,在2Sum问题中,定义首尾两个指针,判断该指针对应两个数的和,若大于target,则尾指针向前移动,小于target则首指针向后移动,知道尾指针小于或者等于首指针时,循环结束。且在其中需要去除重复出现的组合,此时当遇到与前一个相同的数字时,跳过改数字。

C++算法实现如下:

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    vector<vector<int> > threeSum(vector<int>& nums) {
        vector<vector<int> > result;
        bool flag;
        sort(nums.begin(),nums.end());
        for(int i=0;i<nums.size();i++){
            if(i>0&&nums[i]==nums[i-1])
                continue;
            int target=0-nums[i];
            int j=i+1;
            int k=nums.size()-1;
            while(j<k){
                if(nums[j]+nums[k]==target){
                    vector<int> temp;
                    temp.push_back(nums[i]);
                    temp.push_back(nums[j]);
                    temp.push_back(nums[k]);
                    result.push_back(temp);
                    while (j < k && nums[j] == nums[j + 1]) ++j;//重复元素跳过
                    while (i < k && nums[k] == nums[k - 1]) --k;
                    k--;
                    j++;
                }else if(nums[j]+nums[k]>target){//两数之和大于目标值,则尾指针向前移动
                    k--;
                }else{
                    j++;
                }   
            }         
        }
        return result;
    }
};
int main(){
    vector<vector<int> > result;
    int d[6]={-1, 0, 1, 0, 0, -4};
    vector<int> data;
    for(int i=0;i<6;i++){
        data.push_back(d[i]);
    }

    Solution sol;
    result=sol.threeSum(data);
    for(int i=0;i<result.size();i++){
        for(int j=0;j<result[i].size();j++){
            cout<<result[i][j]<<" ";
        }
        cout<<endl;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值