leetcode15—3Sum

Given an array nums of n integers, are there elements a, b, c 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.如果为0
添加到vector中,如果和大于0,指向尾端元素的指针执行自减操作。如何和小于0,指向固定点位置后一个元素的指针执行自增操作.
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        int len = nums.size();
        vector<vector<int>> result;
        if(0 == len)
            return result;
        sort(nums.begin(),nums.end());
        for(int i = 0 ; i < len ; i++){
            int front = i+1;
            int end = len - 1;
            if(i != 0 && nums.at(i) == nums.at(i-1))
                continue;//跳过重复情况
            while(front < end ){
                if(nums.at(i) + nums.at(front)+nums.at(end) == 0){
                  result.push_back({nums.at(i),nums.at(front),nums.at(end)});
                    front++;
                    end--;
                    while(front < end && nums.at(front) == nums.at(front-1))
                        front++;//避免front对应的值重复
                    while(front < end && nums.at(end) == nums.at(end+1))
                        end--;//避免end对应的值重复
                    
                }else if(nums.at(i) + nums.at(front) + nums.at(end) < 0){
                    front++;
                }else{
                    end--;
                }    
            }
        }
        return result;
        
    }
};

猜你喜欢

转载自www.cnblogs.com/tingweichen/p/9954529.html
今日推荐