leetcode 18 4Sum
2016-06-22 21:57
357 查看
leetcode 18 4Sum
原题链接:https://leetcode.com/problems/4sum/Description
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: 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] ]
Solution
二分查找,先预先枚举出a+b所得的n2个数字并排好序。然后判断是否有a+b=target−c−d(二分查找即可)
PS: 注意所求的四个数下标各不相同,枚举的时候要加以判断
PPS: 所得结果可能需要去重。
class Solution { using vec = vector<int>; using mat = vector<vec>; using pii = pair<int, pair<int, int>>; public: mat fourSum(vec& nums, int target) { mat res; int n = 0; if(!(n = nums.size()) || n < 4) return res; vector<pii> vpi; for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { vpi.push_back({ nums[i] + nums[j], { i, j } }); } } sort(vpi.begin(), vpi.end(), [](pii &a, pii &b)->bool { return a.first < b.first; }); int size = vpi.size(); for(int i = 0; i < n; i++) { for(int j = i + 1; j < n; j++) { int lb = 0, ub = size - 1; int k = target - nums[i] - nums[j]; while(lb <= ub) { int m = (lb + ub) >> 1; if(vpi[m].first >= k) ub = m - 1; else lb = m + 1; } while(lb < size && vpi[lb].first == k) { auto &r = vpi[lb++].second; if(r.first == i || r.first == j || r.second == i || r.second == j) continue; int a = nums[i], b = nums[j], c = nums[r.first], d = nums[r.second]; if(a + b + c + d != target) continue; if (a > b) swap(a, b); if (c > d) swap(c, d); if (a > c) swap(a, c); if (b > d) swap(b, d); if (b > c) swap(b, c); res.push_back({ a, b, c, d }); } } } sort(res.begin(), res.end()); res.erase(unique(res.begin(), res.end()), res.end()); return res; } };
相关文章推荐
- 数组
- 关爱码农成长:关于写代码二三事
- C/C++代码检视实例
- 【转】UITableView详解(UITableViewCell
- 将十六进制的颜色字符串转为UIColor
- linux开启某个端口
- 增量式旋转编码器的试验数据
- LAMPA搭建
- numpy中矩阵转置
- C#实现通过模板自动创建Word文档的方法
- spring集合类型的setter注入的一个简单例子
- Scrapy之探讨3个细节
- Gartner: 2016年十大安全预测
- hrbust 1547 基础数据结构——单链表(2)【水题-暴力预处理】
- LTE MIB&SIB1
- 测试用例之性能测试用例
- 时间复杂度和空间复杂度
- 【混淆矩阵】matlab画混淆矩阵
- 关于海量数据查找排序问题
- php 学习笔记 一