3Sum

2017-10-04 16:30:13

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]
]
主要思路:先排序,然后利用双指针法,注意去重。有三处要去重。
 1 class Solution {
 2 public:
 3     vector<vector<int>> threeSum(vector<int>& nums) {
 4         //双指针法
 5         vector<vector<int>> res;
 6         vector<int> temp;
 7         sort(nums.begin(),nums.end());
 8         //先排序,用于去重。
 9         for(int i=0;i<nums.size();i++){
10             int front=i+1,back=nums.size()-1;
11             int target=-nums[i];
12             while(front<back){
13                 if(target<nums[front]+nums[back])  back--;
14                 else if(target>nums[front]+nums[back]) front++;
15                 else{
16                     temp.push_back(nums[i]);
17                     temp.push_back(nums[front]);
18                     temp.push_back(nums[back]);
19                     res.push_back(temp);
20                     
21                     while(front<back&&nums[front]==temp[1])  front++;
22                     while(front<back&&nums[back]==temp[2])  back--;
23                     temp.clear();
24                 }
25             }
26             while(i+1<nums.size()&&nums[i]==nums[i+1])  i++;
27         }
28         return res;
29     }
30 };

 

posted on 2017-10-04 16:44  wsw_seu  阅读(101)  评论(0编辑  收藏  举报

导航