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.java
Note:數組
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
大致的思想先將數組排序,從小到大取vector中的數first,再從剩下的數中取和等於 0 - first 的數便可。下面是代碼(一開始沒想出來,而後參考了別人的解法在寫出來,通常的三層循環誰都能想到,可是時間複雜度過高,這裏的這個時間複雜度應該是O(N^2),仍是能夠接受的)
1 class Solution { 2 public: 3 vector<vector<int>> threeSum(vector<int>& nums) 4 { 5 vector<vector<int>> result; 6 int sz = nums.size(); 7 sort(nums.begin(), nums.end()); 8 for (int i = 0; i < sz - 2; ++i){ 9 twoSum(nums, i + 1, 0 - nums[i], result); 10 while(nums[i] == nums[i + 1]) ++i;//這一步要注意,防止得出重複的vector 11 } 12 return result; 13 } 14 15 void twoSum(vector<int> & nums, int start, int value, vector<vector<int>> & ret) 16 { 17 int beg = start; 18 int end = nums.size()-1; 19 while (beg < end){ 20 int sum = nums[beg] + nums[end]; 21 if (sum < value) 22 beg++; 23 else if (sum > value) 24 end--; 25 else{ 26 ret.push_back(vector<int>{nums[start - 1], nums[beg], nums[end]}); 27 while (nums[beg + 1] == nums[beg]) beg++;//這一步的處理應該注意,防止出現相同的vector 28 while (nums[end - 1] == nums[end]) end--; 29 beg++, end--; 30 } 31 } 32 } 33 };
java版的代碼以下所示:spa
(因爲不太熟悉ArrayList和List之間的關係,寫起來感受各類坑爹啊,注意下List和ArrayList之間的各類轉換就能夠了,代碼以下):code
1 public class Solution { 2 List<List<Integer>> ret = new ArrayList<List<Integer>>(); 3 4 public List<List<Integer>> threeSum(int[] nums) { 5 Arrays.sort(nums); 6 for(int i = 0; i < nums.length - 2; ++i){ 7 twoSum(nums, i+1, 0 - nums[i]); 8 while(i < nums.length - 2 && nums[i] == nums[i+1]) 9 ++i; 10 } 11 return ret; 12 } 13 14 public void twoSum(int[] nums, int start, int value) 15 { 16 int beg = start; 17 int end = nums.length - 1; 18 while(beg < end){ 19 if(nums[beg] + nums[end] == value){ 20 List<Integer> list = new ArrayList<Integer>(); 21 list.add(nums[start - 1]); 22 list.add(nums[beg]); 23 list.add(nums[end]); 24 ret.add(list); 25 while(beg < end && nums[beg+1] == nums[beg]) 26 beg++; 27 while(beg < end && nums[end-1] == nums[end]) 28 end--; 29 beg++; 30 end--; 31 32 }else if(nums[beg] + nums[end] > value){ 33 end--; 34 }else{ 35 beg++; 36 } 37 } 38 } 39 }
PS:一樣的4Sum問題也能夠轉換成上面的3Sum問題,從而遞歸的求解,KSum問題也是同樣blog