Given an array nums
of n integers, are there elements a, b, c in nums
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.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
题意
在给定数组中找三个数和为0
题解
用了set储存答案防止重复,很慢
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) { 4 sort(nums.begin(), nums.end()); 5 set<vector<int>> ans; 6 for (int i = 0; i < nums.size(); i++) { 7 if (nums[i] > 0)break; 8 int j = i + 1, k = nums.size() - 1; 9 while (j < k) { 10 if (nums[j] + nums[k] == 0 - nums[i]) { 11 vector<int>tmp; 12 tmp.push_back(nums[i]); 13 tmp.push_back(nums[j]); 14 tmp.push_back(nums[k]); 15 ans.insert(tmp); 16 j++,k--; 17 } 18 else if (nums[j] + nums[k] < 0 - nums[i])j++; 19 else k--; 20 } 21 } 22 vector<vector<int>> _ans; 23 while (!ans.empty()) { 24 auto tmp = *(ans.begin()); 25 ans.erase(ans.begin()); 26 _ans.push_back(tmp); 27 } 28 return _ans; 29 } 30 };
于是换了一下……
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) { 4 sort(nums.begin(), nums.end()); 5 vector<vector<int>> ans; 6 for (int i = 0; i < nums.size(); i++) { 7 if (nums[i] > 0)break; 8 if (i > 0 && nums[i] == nums[i - 1])continue; 9 int j = i + 1, k = nums.size() - 1; 10 while (j < k) { 11 if (nums[j] + nums[k] == 0 - nums[i]) { 12 vector<int>tmp; 13 tmp.push_back(nums[i]); 14 tmp.push_back(nums[j]); 15 tmp.push_back(nums[k]); 16 while (j < k&&nums[j] == nums[j + 1])j++; 17 while (j < k&&nums[k] == nums[k - 1])k--; 18 ans.push_back(tmp); 19 j++, k--; 20 } 21 else if (nums[j] + nums[k] < 0 - nums[i])j++; 22 else k--; 23 } 24 } 25 return ans; 26 } 27 };
差得好多哦-。-