15 3Sum

15 3Sum

链接:https://leetcode.com/problems/3sum/
问题描述:
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)

Hide Tags Array Two Pointers
Hide Similar Problems (M) Two Sum (M) 3Sum Closest (M) 4Sum

给出数组,求数组中所有三个数的和为0的组合。思路是这样的:
1 将数组排序。
2 从前往后取数字。取玩一个数字后,初始化两个‘指针’,p1指向之后的一个数字,p2指向最后一个数字。
3 求和如果等于0,则记录结果。如果大于0则p2–。如果小于0则p1++。
4 利用一些条件可以加速,否则容易通不过。

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {

        vector<vector<int>> result;
        int p1,p2;

        sort(nums.begin(),nums.end());
        for(int i=0;i<(int)nums.size()-2;i++)
        {
                if(i > 0 && nums[i]==nums[i-1])  
                continue;  
                else if(nums[i]>0)
                break;

                p1=i+1;
               p2=nums.size()-1;
               while(p1<p2)
               {
                   if(p1>i+1&&nums[p1]==nums[p1-1])
                   {
                       p1++;
                       continue;
                   }
                   else if(p2<nums.size()-1&& nums[p2]==nums[p2+1])
                   {
                       p2--;
                      continue;
                   }
                   else if(nums[i]+nums[p1]>0)
                   break;
                   else if(nums[i]+nums[p1]+nums[p2]==0)
                   {
                      vector<int> temp;
                      temp.push_back(nums[i]);
                      temp.push_back(nums[p1]);
                      temp.push_back(nums[p2]);
                      result.push_back(temp);
                      p1++;

                   }
                   else if(nums[i]+nums[p1]+nums[p2]<0)
                      p1++;
                   else
                       p2--;
               }   
        }

        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值