LeetCode15. 3Sum(C++)

Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

解题思路:先将数组排序,然后开始遍历,先确定一个数,遇到这个数与前面的数相同时,则跳过,然后用双指针法,在该数的右边找两个数使得这三个数相加为0;

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        vector<vector<int>>result;
        for(int i=0;i<nums.size();i++){
            while(i!=0&&nums[i-1]==nums[i]) i++;
            int sum=0-nums[i];
            int low=i+1,high=nums.size()-1;
            while(low<high){
                int temp=nums[low]+nums[high];
                if(temp==sum){
                    vector<int>tempresult(3);
                    tempresult[0]=nums[i];
                    tempresult[1]=nums[low++];
                    tempresult[2]=nums[high--];
                    result.push_back(tempresult);
                    while(low<high&&nums[low]==tempresult[1]) low++;
                    while(low<high&&nums[high]==tempresult[2]) high--;
                }
                else if(temp>sum)
                    high--;
                else
                    low++;
            }
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41562704/article/details/86094658