3 sums题解

来源:互联网 发布:网络造字 编辑:程序博客网 时间:2024/05/21 19:03

题干:
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)

Difficulty: Medium
翻译:
给一个数列和一个目标target,找三个数,相加之和是target,并且三个数不能是重复点,要递增顺序
分析:
sum系列题的第二道,跟2sum和4sums是承上启下的作用,实际上这题有两种解法,一种是转化成上一道题,不过外面套一个for循环,然后把问题转化为2sum,另一种解法是用三个指针,一个指针指向当前元素,定位num1,另外两个指针在num1-(n-1)的位置两头开始,往中间走,找num2和num3,两种方法的唯一区别就在于是否利用辅助空间,时间复杂度都是一样的O(n²)
sum系列一共有4道题,我们这两道用map,下两道用指针:

class Solution {public:    vector<vector<int>> threeSum(vector<int>& nums) {        vector<vector<int>> ret;        if (nums.size() <= 2)            return ret;        map<int, int> Hash_map;        sort(nums.begin(), nums.end());        for (int i = 0; i < nums.size(); i++)            Hash_map[nums[i]] = i;            //加一层for循环        for (int i = 0; i < nums.size(); i++) {            int target = 0 - nums[i];            vector<int> curr;            //内部完全是2sum问题            for (int j = i + 1; j < nums.size(); j++) {                int rest_val = target - nums[j];                if (Hash_map.find(rest_val) != Hash_map.end()) {                    int index = nums[rest_val];                    if (index == j || index == i) continue;                    if (index > j) {                        curr.push_back(nums[i]);                        curr.push_back(nums[j]);                        curr.push_back(nums[index]);                        ret.push_back(curr);                    }                }                while (j < nums.size() - 1 && nums[j] == nums[j + 1]) j++;            }            while (i < nums.size() - 1 && nums[i] == nums[i + 1]) i++;        }        for (int i = 0; i < ret.size(); i++) {            if(equal(ret[i],ret[i+1]))        }        return ret;    }};

时间复杂度为O(n²),空间复杂度为O(n)

0 0
原创粉丝点击