LeetCode:4Sum
来源:互联网 发布:taptap类似的软件 编辑:程序博客网 时间:2024/06/06 02:47
Given an array S of n integers, are there elementsa, 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)解题思路: 由于最终结果集中的四元组是非降序的,所以事先对序列进行排序,然后分别枚举c,d的位置.去重的做法与3Sum的做法类似,只是多了一重循环.时间复杂度为O(N^3).解题代码:class Solution {public: vector<vector<int> > fourSum(vector<int> &num, int target) { sort(num.begin(),num.end()); vector<vector<int> > res; int n = num.size() , arr[4] ; bool flag = false; for(int d = n - 1 ; d > 2 ; --d) { if( d < n - 1 && num[d] == num[d+1]) continue; for(int c = d - 1 ; c > 1 ; --c) { if( c < d - 1 && num[c] == num[c+1]) continue; int a = 0 , b = c - 1 ; while( a < b) { long long sum = num[a] + num[b] + num[c] + num[d] ; if(sum == target) { if(!flag) { arr[0] = num[a] , arr[1] = num[b] , arr[2] = num[c] , arr[3] = num[d]; res.push_back(vector<int>(arr,arr+4)); flag = true; } else if(arr[0] != num[a] || arr[1] != num[b] || arr[2] != num[c] || arr[3] != num[d]) { arr[0] = num[a] , arr[1] = num[b] , arr[2] = num[c] , arr[3] = num[d]; res.push_back(vector<int>(arr,arr+4)); } ++a , --b ; continue; } sum > target ? --b : ++a ; } } } return res; }};
0 0
- 【Leetcode】4Sum (Sum)
- leetcode 2 sum 3sum 4sum
- Leetcode 2SUM-3SUM-4SUM
- Leetcode-2sum,3sum,4sum
- leetcode 2 sum & 3 sum & 4 sum
- [LeetCode] 2Sum, 3Sum, 4Sum, 3SUm closet
- [LeetCode] K sum(2Sum、3Sum、4Sum)
- leetcode--sum集合:2sum,3sum,4sum
- leetcode --- 2 sum , 3 sum , 4 sum , k sum problem
- LeetCode: 4 Sum
- LeetCode: 4Sum
- LeetCode 4Sum
- Leetcode: 4SUM
- 【leetcode】 4 sum
- LeetCode 4Sum
- leetcode 44: 4Sum
- [Leetcode] 4 Sum [Unsolved]
- 【leetcode】4Sum
- linux和window当前目录
- 三星Galaxy Tab S超强平板显示屏现身
- Unity3d 实时折射与反射
- Java基础类库
- 照片出现破损丨怎么恢复
- LeetCode:4Sum
- 农民发明载人行李箱:可乘2人,时速20公里
- gdb调试多进程和多线程
- 红黑树和AVL树的比较
- 我们需要怎样的OLAP
- JS中的call()和apply()方法
- Ubuntu下wxWidgets学生信息管理soci
- 微信对联系人数量设上限,打击朋友圈恶意营销
- CURL常用命令