15、3Sum
阿新 • • 發佈:2017-11-09
ucc proc triplets efault expect finding art ack -s
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] ]
第一遍寫了下面的代碼,是錯的:
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> answers; int n=0; if(nums.empty() || nums.capacity() < 3) return answers; for(int i=0; i < nums.capacity() - 2; i++)for(int j = i + 1; j < nums.capacity() - 1; j++) for(int k = j + 1; k < nums.capacity(); k++) if(nums[i] + nums[j] + nums[k] == 0){ vector<int> answer; answer.push_back(nums[i]); answer.push_back(nums[j]); answer.push_back(nums[k]); answers.push_back(answer); }return answers; } };
Submission Result: Wrong Answer More Details
Input:[-1,0,1,2,-1,-4] Output:[[-1,0,1],[-1,2,-1],[0,1,-1]] Expected:[[-1,-1,2],[-1,0,1]] 顯然有重復的 [-1,0,1]和[0,1,-1]是算為一樣的——————————————————————————————————————————————————————————————————————
第二遍先對nums排序,代碼也是錯的:
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> answers; std::sort(nums.begin(), nums.end()); //對nums排序 int n=0,flag=0; if(nums.empty() || nums.capacity() < 3) return answers; for(int i=0; i < nums.capacity() - 2; i++){ if(i>0 && nums[i] == nums[i - 1]) continue; //如果當前元素等於前一個元素,跳過,防止出現重復配對 for(int j = i + 1; j < nums.capacity() - 1; j++) for(int k = j + 1; k < nums.capacity(); k++) if(nums[i] + nums[j] + nums[k] == 0){ vector<int> answer; answer.push_back(nums[i]); answer.push_back(nums[j]); answer.push_back(nums[k]); answers.push_back(answer); } } return answers; } };
結果沒通過:
Input:[0,0,0,0] Output:[[0,0,0],[0,0,0],[0,0,0]] Expected:[[0,0,0]] ———————————————————————————————————————————————————————————————————————— 最終沒做對,做了一兩個小時沒做對。。。。看答案:class Solution { public: vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int> > res; std::sort(num.begin(), num.end()); for (int i = 0; i < num.size(); i++) { int target = -num[i]; int front = i + 1; int back = num.size() - 1; while (front < back) { int sum = num[front] + num[back]; // Finding answer which start from number num[i] if (sum < target) front++; else if (sum > target) back--; else { vector<int> triplet(3, 0); triplet[0] = num[i]; triplet[1] = num[front]; triplet[2] = num[back]; res.push_back(triplet); // Processing duplicates of Number 2 // Rolling the front pointer to the next different number forwards while (front < back && num[front] == triplet[1]) front++; // Processing duplicates of Number 3 // Rolling the back pointer to the next different number backwards while (front < back && num[back] == triplet[2]) back--; } } // Processing duplicates of Number 1 while (i + 1 < num.size() && num[i + 1] == num[i]) i++; } return res; } };
15、3Sum