15. 3Sum
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]
]
此題的結題思想其實和TwoSum一樣,當我們確定了第一個數字后,第二個和第三個數字就可以用TwoSum一樣的解法求得。 唯一的區別是TwoSum這題只有唯一解,而 3Sum這題可能有多個相同的解,我們需要考慮怎么移除相同的解。
因為返回的是具體的三個數字,而不是數字的下標,所以可以考慮先將輸入的序列進行排序。得到排序后的序列num,長度為n。
將num[i]作為第一個值,檢查序列后面的值中第一個和最后一個值的和 sum = num[i + 1] + num[n-1] 是否等于 target = -num[0]。若sum < target,則說明后兩個值偏小,前一個值贏得后移。否則,若sum > target,則說明后兩個的值偏大,后一個值應當左移。否則,若sum == target,此時找到正確解,暫時保存這3個值。同時應當考慮可能存在的相同的解。因為第一個值已經固定,只需考慮后面2個數不重復出現即可。最后,還要考慮第一個值也可能與后面的值相同。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]) rear--; } } // Processing duplicates of Number 1 while (i + 1 < num.size() && num[i + 1] == num[i]) i++; } return res;}github:https://github.com/Subenle/LeetCode-in-Cpp/blob/master/015.md
新聞熱點
疑難解答