原題以下:
數組
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.spa
Note:
.net
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)code
The solution set must not contain duplicate triplets.orm
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
這道題讓我想起了Leetcode的第一道題,即2Sum。不少人跟我說這兩道題很像,可是我作完以後感受一點都不像。blog
在2Sum這道題裏面,Leetcode對時間的要求很高,因此用的是hash table的思想來解決的,即把value爲key,position做爲value,若是有衝突的話能夠在一個bucket裏放多個value。這樣的話複雜度就只有O(n)。排序
3Sum不同,是肯定一個值以後來肯定另外兩個值。肯定另外兩個值複雜度最低也是O(n),因此整體的複雜度是O(n^n)。three
仔細觀察題目,第一個要求是要將數組以增序輸出,因此咱們最好將整個數組排序,複雜度爲O(n^n),最低爲O(nlogn)(使用快排)。排序對後面的掃描是至關有用的。ip
第二個要求是不能重複。初看上去挺難的,其實很簡單,只須要在掃描的過程當中跳太重複的既可。element
代碼以下,思路比較簡單:
class Solution { public: vector< vector<int> > threeSum(vector<int>& nums) { vector< vector<int> > result; result.clear(); unsigned int i; unsigned int j; unsigned int k; int sum; if (nums.size() < 3) { return result; } bubble_sort(nums); //首先進行從小到大排序 i = 0; while (i < nums.size() - 2) { j = i + 1; k = nums.size() - 1; while (j < k) { sum = nums[i] + nums[j] + nums[k]; if (0 == sum) //和爲0時,須要去除那些重複的數字 { vector<int> triplet; triplet.push_back(nums[i]); triplet.push_back(nums[j]); triplet.push_back(nums[k]); result.push_back(triplet); //去除重複 while (j < k && nums[j] == triplet[1]) j++; //去重又自增,這個循環總會執行至少一遍 while (j < k && nums[k] == triplet[2]) k--; } else if (sum > 0) //和大於0,k必須向左移動下降組合的值 { k--; } else { j++; } } int temp = nums[i]; while (i < nums.size() - 2 && nums[i] == temp) i++; } return result; } private: void bubble_sort(vector<int>& nums) //冒泡排序 { bool is_swap; for (unsigned int i = nums.size() - 1; i > 0; i--) { is_swap = false; for (unsigned int j = 0; j < i; j++) { if (nums[j] > nums[j+1]) { swap(nums[j], nums[j+1]); is_swap = true; } } if (false == is_swap) { break; } } } void swap(int& a, int& b) { int temp = a; a = b; b = temp; } };
參考文章: