4Sum Solutions in C++
Number 18
Difficulty Medium
Acceptance 33.7%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/4sum/// Author : Hao Chen// Date : 2014-07-03#include <iostream>#include <vector>#include <algorithm>using namespace std;vector<vector<int> > threeSum(vector<int> num, int target);/** 1) Sort the array,* 2) traverse the array, and solve the problem by using "3Sum" soultion.*/vector<vector<int> > fourSum(vector<int> &num, int target) {vector< vector<int> > result;if (num.size() < 4) return result;sort( num.begin(), num.end() );for(int i = 0; i < num.size() - 3; i++) {//skip the duplicationif (i > 0 && num[i - 1] == num[i]) continue;vector<int> n(num.begin()+i+1, num.end());vector<vector<int> > ret = threeSum(n, target-num[i]);for(int j = 0; j < ret.size(); j++) {ret[j].insert(ret[j].begin(), num[i]);result.push_back(ret[j]);}}return result;}vector<vector<int> > threeSum(vector<int> num, int target) {vector< vector<int> > result;//sort the array (if the qrray is sorted already, it won't waste any time)sort(num.begin(), num.end());int n = num.size();for (int i = 0; i < n - 2; i++) {//skip the duplicationif (i > 0 && num[i - 1] == num[i]) continue;int a = num[i];int low = i + 1;int high = n - 1;while (low < high) {int b = num[low];int c = num[high];if (a + b + c == target) {//got the soultionvector<int> v;v.push_back(a);v.push_back(b);v.push_back(c);result.push_back(v);// Continue search for all triplet combinations summing to zero.//skip the duplicationwhile(low < n && num[low] == num[low + 1]) low++;while(high > 0 && num[high] == num[high - 1]) high--;low++;high--;} else if (a + b + c > target) {//skip the duplicationwhile(high > 0 && num[high] == num[high - 1]) high--;high--;} else {//skip the duplicationwhile(low < n && num[low] == num[low + 1]) low++;low++;}}}return result;}int printMatrix(vector< vector<int> > &vv){for(int i = 0; i < vv.size(); i++) {cout << "[";for(int j = 0; j < vv[i].size(); j++) {cout << " " << vv[i][j];}cout << "]" << endl;;}}int main(){int a[] = { 1, 0, -1, 0, -2, 2 };vector<int> n(a, a+6);int t = 0;vector< vector<int> > v = fourSum(n, t);printMatrix(v);n.clear();int b[] = { -1, -5, -5, -3, 2, 5, 0, 4 };n.insert(n.begin(), b, b+8);t = -7;v = fourSum(n, t);printMatrix(v);return 0;}
C++ solution by pezy/LeetCode
#include <vector>using std::vector;#include <algorithm>#include <unordered_map>#include <set>class Solution {public:vector<vector<int> > fourSum(vector<int> &num, int target) {if (num.size() < 4) return vector<vector<int>>{};std::set<vector<int>> ret;std::sort(num.begin(), num.end());std::unordered_map<int, vector<std::pair<int, int>>> cache;for (size_t i=0; i<num.size(); ++i)for (size_t j=i+1; j<num.size(); ++j)cache[num[i]+num[j]].emplace_back(i, j);for (const auto &rp : cache) {auto found = cache.find(target - rp.first);if (found != cache.end())for (const auto &low : rp.second)for (const auto &high : found->second)if (low.second < high.first) ret.insert(vector<int>{num[low.first], num[low.second], num[high.first], num[high.second]});}return vector<vector<int>>(ret.cbegin(), ret.cend());}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/4sum//// Author : liuyubobobo/// Time : 2016-12-06#include <iostream>#include <vector>#include <cassert>#include <stdexcept>using namespace std;/// Two pointers/// Sort the array first./// For every different number a and b, try to find a pair (c, d), which a + b + c + d == 0/// Using this way, we don't need to see whether the triplet is a repeated one////// Time Complexity: O(nlogn) + O(n^3)/// Space Complexity: O(1)class Solution {public:vector<vector<int>> fourSum(vector<int>& nums, int target) {int n = nums.size();vector<vector<int>> res;if(n < 4)return res;sort(nums.begin(), nums.end());for(int i = 0 ; i <= n - 4 ; i = nextNumberIndex(nums, i))for (int j = i + 1; j <= n - 3; j = nextNumberIndex(nums, j)) {int t = target - nums[i] - nums[j];if(nums[j+1] + nums[j+2] > t || nums[n-1] + nums[n-2] < t)continue;int p1 = j + 1;int p2 = nums.size() - 1;if (p1 >= p2)break;while (p1 < p2) {if (nums[p1] + nums[p2] == t) {res.push_back({nums[i], nums[j], nums[p1], nums[p2]});p1 = nextNumberIndex(nums, p1);p2 = preNumberIndex(nums, p2);}else if (nums[p1] + nums[p2] < t)p1 = nextNumberIndex(nums, p1);else // nums[p1] + nums[p2] > tp2 = preNumberIndex(nums, p2);}}return res;}private:int nextNumberIndex( const vector<int> &nums , int index ){for( int i = index + 1 ; i < nums.size() ; i ++ )if( nums[i] != nums[index] )return i;return nums.size();}int preNumberIndex( const vector<int> &nums , int index ){for( int i = index-1 ; i >= 0 ; i -- )if( nums[i] != nums[index] )return i;return -1;}};void print_vec(const vector<vector<int>>& vec){for(const vector<int>& v: vec){for(int e: v)cout << e << " ";cout << endl;}}int main() {vector<int> nums1 = {1, 0, -1, 0, -2, 2};int target1 = 0;print_vec(Solution().fourSum(nums1, target1));return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/4sum//// Author : liuyubobobo/// Time : 2017-09-27#include <iostream>#include <vector>#include <cassert>#include <stdexcept>#include <unordered_map>#include <algorithm>using namespace std;/// Using hash table/// Sort the array first./// Store every different c + d == t first/// For every different number a and b, try to find a pair (c, d), which a + b + c + d == 0////// Time Complexity: O(nlogn) + O(n^2) + O(n^3)/// Space Complexity: O(n^2)class Solution {public:vector<vector<int>> fourSum(vector<int>& nums, int target) {int n = nums.size();vector<vector<int>> res;if(n < 4)return res;sort(nums.begin() , nums.end());unordered_map<int, vector<pair<int, int>>> hashtable;for(int i = 0 ; i < n - 1 ; i = nextNumberIndex(nums, i))for(int j = i + 1 ; j < n ; j = nextNumberIndex(nums, j))hashtable[nums[i]+nums[j]].push_back(make_pair(nums[i], nums[j]));for( int i = 0 ; i <= n - 4 ; i = nextNumberIndex(nums, i) )for (int j = i + 1; j <= n - 3; j = nextNumberIndex(nums, j)) {int t = target - nums[i] - nums[j];if( nums[j+1] + nums[j+2] > t || nums[n-1] + nums[n-2] < t)continue;if(hashtable.find(t) == hashtable.end())continue;vector<pair<int,int>>::iterator iter =lower_bound(hashtable[t].begin(), hashtable[t].end(), make_pair(nums[j+1], nums[j+1]));for(; iter != hashtable[t].end() ; iter ++)res.push_back({nums[i], nums[j], iter->first, iter->second});}return res;}private:int nextNumberIndex( const vector<int> &nums , int index ){for( int i = index + 1 ; i < nums.size() ; i ++ )if( nums[i] != nums[index] )return i;return nums.size();}int preNumberIndex( const vector<int> &nums , int index ){for( int i = index-1 ; i >= 0 ; i -- )if( nums[i] != nums[index] )return i;return -1;}};void print_vec(const vector<vector<int>>& vec){for(const vector<int>& v: vec){for(int e: v)cout << e << " ";cout << endl;}}int main() {vector<int> nums1 = {1, 0, -1, 0, -2, 2};int target1 = 0;print_vec(Solution().fourSum(nums1, target1));return 0;}