首页 > 代码库 > [LeetCode] 15. 3Sum

[LeetCode] 15. 3Sum

Given an array S of n integers, are there elements abc 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         vector<vector<int>> ret; 5          6         sort(nums.begin(), nums.end()); 7          8         for (int i = 0; i < nums.size(); i++){ 9             // if i is  scanced already, skip it10             if (i > 0 && nums[i] == nums[i-1]) continue;11             int left = i + 1;12             int right = nums.size() - 1;13             while (left < right){14                 if ((nums[left] + nums[right]) < -nums[i]){15                     left++;16                 }else if ((nums[left] + nums[right]) > -nums[i]){17                     right--;18                 }else{19                     vector<int> tmp;20                     tmp.push_back(nums[i]);21                     tmp.push_back(nums[left]);22                     tmp.push_back(nums[right]);23                     ret.push_back(tmp);24                     left++;25                     right--;26                     // remove duplicates!27                     while(nums[left] == nums[left - 1]) left++;28                     while(nums[right] == nums[right+1]) right--;        29                 }30             }31         }32         33         return ret;34     }35 };

 

[LeetCode] 15. 3Sum