15. 3Sum

来源:互联网 发布:域名找回 编辑:程序博客网 时间:2024/06/18 08:41

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]]

这道题如果强行遍历的话,时间复杂度是O(n3),非常耗时。这道题可以使用STL中的sort() 函数先对数组进行排序,然后再第二轮遍历中采用从中间向两边遍历的方法,找出符合条件的三个数。为了避免重复,可以采用set结构。这道题只有采用巧妙的算法,并且熟悉STL的使用才能做好。

class Solution {public:    vector<vector<int>> threeSum(vector<int>& nums) {        set<vector<int>> ans;        sort(nums.begin(), nums.end());        for (int i = 0; i < nums.size(); i++) {            if (nums[i] > 0) break;            int target = 0 - nums[i];            int j = i + 1, k = nums.size() - 1;            while (j < k) {                if (nums[j] + nums[k] == target) {                    ans.insert({nums[i], nums[j], nums[k]});                    while (j < k && nums[j] == nums[j+1]) j++;                    while (j < k && nums[k] == nums[k-1]) k--;                    j++;                    k--;                }                else if (nums[j] + nums[k] < target) j++;                else k--;            }        }        return vector<vector<int>>(ans.begin(), ans.end());    }};
原创粉丝点击