首页 > 代码库 > [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)
跟3Sum一样,先用两层循环,注意去重。
1 class Solution { 2 public: 3 vector<vector<int> > fourSum(vector<int> &num, int target) { 4 vector<vector<int> > res; 5 vector<int> v(4); 6 int sum; 7 if (num.size() < 4) return res; 8 sort(num.begin(), num.end()); 9 for (int i = 0; i < num.size() - 3; ++i) { 10 if (i > 0 && num[i] == num[i-1]) 11 continue; 12 for (int j = i + 1; j < num.size() - 2; ++j) { 13 if (j > i + 1 && num[j] == num[j-1]) 14 continue; 15 int low = j + 1, high = num.size() - 1; 16 while (low < high) { 17 sum = num[i] + num[j] + num[low] + num[high]; 18 if (sum > target) { 19 --high; 20 } else if (sum < target) { 21 ++low; 22 } else { 23 v[0] = num[i]; 24 v[1] = num[j]; 25 v[2] = num[low]; 26 v[3] = num[high]; 27 res.push_back(v); 28 while (low < num.size() && num[low+1] == num[low]) ++low; 29 while (high > 0 && num[high-1] == num[high]) --high; 30 ++low; --high; 31 } 32 } 33 } 34 } 35 return res; 36 } 37 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。