leetcode 15. 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: 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]
]

题目的意思是求满足三个数的和为0的元组,元组不能重复
思路:
枚举c的值,然后再找满足a+b=0的a,b值。为了避免重复,先排序
用unorder_map写了一份代码,时间复杂度O(lognn^2+nlogn)超时...
后来用双指针通过时间复杂度O(n^2+nlogn)。

class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int> > w;
        int n = nums.size();
        if (n < 3) return w;
        int l, r, c;
        for (int i = 0; i < n; ++i) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            l = i + 1, r = n - 1;
            c = -nums[i];
            while (l < r) {
                int sum = nums[l] + nums[r];
                if (sum == c) {
                    vector<int> v(3);
                    v[0] = nums[i];
                    v[1] = nums[l];
                    v[2] = nums[r];
                    w.push_back(v);
                    while (l > 0 && nums[l] == nums[l + 1]) ++l;
                    while (r < n && nums[r] == nums[r - 1]) --r;
                }
                if (sum > c) --r;
                else ++l;
            } 
        }
        return w;
    }
};
posted on 2017-09-04 15:04  Beserious  阅读(158)  评论(0编辑  收藏  举报