首页 > 代码库 > [LeetCode] 4Sum
[LeetCode] 4Sum
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
-
-
- Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
- The solution set must not contain duplicate quadruplets.
-
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
这题各种面熟,先来暴力的吧。因为要求abcd是递增的,所以可以先将num排序以后再爆,嗯。
我擦咧闹不住暴破法(Time Limit Exceed):
1 vector<vector<int> > fourSum(vector<int> &num, int target) { 2 vector<vector<int>>result; 3 if (num.size() < 4) return result; 4 sort(num.begin(), num.end()); 5 for (int i=0; i<num.size()-3; i++){ 6 for (int j=i+1; j<num.size()-2; j++){ 7 for (int k=j+1; k<num.size()-1; k++){ 8 for (int v=k+1; v<num.size(); v++){ 9 if (num[i]+num[j]+num[k]+num[v] == target){ 10 vector<int>tmp; 11 tmp.push_back(num[i]); 12 tmp.push_back(num[j]); 13 tmp.push_back(num[k]); 14 tmp.push_back(num[v]); 15 result.push_back(tmp); 16 } 17 } 18 } 19 } 20 } 21 return result; 22 }
O(n^4)就是个娱乐,别说大集合没戏,连稍微大一点的集合都过不了的。
看看优化,可以把最后一层循环n变成logn, 思想是最后一层循环实际上是为了从 [k+1, num.size()) 中找到一个数x且x=target - (num[i]+num[j]+num[k]) 。这样我们就可以用二分查找代替遍历,所以原本的O(n^4)就变成了O(n^3 logn)
复杂度依然是难以接受的,但至少比n^4要好一丢丢,期待进一步优化...
我擦咧稍微闹得住一丢丢暴破法(Time Limit Exceed):
1 vector<vector<int> > fourSum(vector<int> &num, int target) { 2 vector<vector<int>>result; 3 if (num.size() < 4) return result; 4 sort(num.begin(), num.end()); 5 for (int i=0; i<num.size()-3; i++){ 6 for (int j=i+1; j<num.size()-2; j++){ 7 for (int k=j+1; k<num.size()-1; k++){ 8 if (binary_search(num.begin()+k+1, num.end(), target - num[i]-num[j]-num[k])){ 9 vector<int>tmp; 10 tmp.push_back(num[i]); 11 tmp.push_back(num[j]); 12 tmp.push_back(num[k]); 13 tmp.push_back(target - num[i]-num[j]-num[k]); 14 result.push_back(tmp); 15 } 16 } 17 } 18 } 19 return result; 20 }
TO BE CONTINUE....
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。