标签:
Well, this problem has a O(n^3) solution similar to 3Sum. That is, fix two elements nums[i] and nums[j] (i < j) and search in the remaining array for two elements that sum to the target - nums[i] - nums[j]. Since i and j both have O(n) possible values and searching in the remaining array for two elements (just like 3Sum that fixes one and search for two other) has O(n) complexity using two pointers (left and right), the total time complexity is O(n^3).
The code is as follows, which should explain itself.
1 vector<vector<int> > fourSum(vector<int>& nums, int target) { 2 sort(nums.begin(), nums.end()); 3 vector<vector<int> > res; 4 for (int i = 0; i < (int)nums.size() - 3; i++) { 5 for (int j = i + 1; j < (int)nums.size() - 2; j++) { 6 int left = j + 1, right = nums.size() - 1; 7 while (left < right) { 8 int temp = nums[i] + nums[j] + nums[left] + nums[right]; 9 if (temp == target) { 10 vector<int> sol(4); 11 sol[0] = nums[i]; 12 sol[1] = nums[j]; 13 sol[2] = nums[left]; 14 sol[3] = nums[right]; 15 res.push_back(sol); 16 while (left < right && nums[left] == sol[2]) left++; 17 while (left < right && nums[right] == sol[3]) right--; 18 } 19 else if (temp < target) left++; 20 else right--; 21 } 22 while (j + 1 < (int)nums.size() - 2 && nums[j + 1] == nums[j]) j++; 23 } 24 while (i + 1 < (int)nums.size() - 3 && nums[i + 1] == nums[i]) i++; 25 } 26 return res; 27 }
In fact, there is also a O(n^2logn) solution, which I will post soon.
标签:
原文地址:http://www.cnblogs.com/jcliBlogger/p/4567868.html