【LeetCode】18. 4Sum (2 solutions)
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)
先确定前两个数num[i],num[j],
然后设置双指针k,l分别指向两端,往中间扫。
(1)(sum = num[i]+num[j]+num[k]+num[l]) == taget,则找到其中一个解。k++,l--.
(2)sum > target, l--
(3)sum < target, k++
解法一:
用map去重
注:不可以使用unordered_map,不然会报错:
error C2440: “类型转换”: 无法从“const std::vector<_Ty>”转换为“size_t”
根据unordered_map的源码来看:
// TEMPLATE CLASS hash
template<class _Kty>
class hash
: public unary_function<_Kty, size_t>
{ // hash functor
public:
size_t operator()(const _Kty& _Keyval) const
{ // hash _Keyval to size_t value by pseudorandomizing transform
ldiv_t _Qrem = _CSTD ldiv((long)(size_t)_Keyval, ); _Qrem.rem = * _Qrem.rem - * _Qrem.quot;
if (_Qrem.rem < )
_Qrem.rem += ;
return ((size_t)_Qrem.rem);
}
};
key必须转换为size_t类型,对应于hash表下标。
保险起见,非内置类型就不要作为unordered_map的key了。
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > result;
if(num.empty() || num.size() < )
return result;
int size = num.size();
sort(num.begin(), num.end());
map<vector<int>, bool> m;
for(int i = ; i < size-; i ++)
{
for(int j = i+; j < size-; j ++)
{
int k = j+; //k < size-1
int l = size-;
while(k < l)
{
int sum = num[i]+num[j]+num[k]+num[l];
if(sum == target)
{
vector<int> cur(,);
cur[] = num[i];
cur[] = num[j];
cur[] = num[k];
cur[] = num[l];
if(m.find(cur) == m.end())
{
result.push_back(cur);
m[cur] = true;
}
k ++;
l --;
}
else if(sum > target)
l --;
else
k ++;
}
}
}
return result;
}
};
解法二:
不用开辟新的空间,通过跳过已访问过的元素来去重。
class Solution {
public:
vector<vector<int> > fourSum(vector<int> &num, int target) {
vector<vector<int> > ret;
int size = num.size();
sort(num.begin(), num.end());
for(int i = ; i < size; i ++)
{
//skip same i
while(i > && i < size && num[i] == num[i-])
i ++;
for(int j = i+; j < size; j ++)
{
//skip same j
//attention: the first element (num[i+1]) should not be skipped
while(j > i+ && j < size && num[j] == num[j-])
j ++; int k = j + ;
int l = size - ;
while(k < l)
{
int sum = num[i] + num[j] + num[k] + num[l];
if(sum == target)
{
vector<int> cur();
cur[] = num[i];
cur[] = num[j];
cur[] = num[k];
cur[] = num[l];
ret.push_back(cur);
k ++;
l --;
//skip same k
while(k < l && num[k] == num[k-])
k ++;
//skip same l
while(l > k && num[l] == num[l+])
l --;
}
else if(sum < target)
{
k ++;
//skip same k
while(k < l && num[k] == num[k-])
k ++;
}
else
{
l --;
//skip same l
while(l > k && num[l] == num[l+])
l --;
}
}
}
}
return ret;
}
};
【LeetCode】18. 4Sum (2 solutions)的更多相关文章
- 【LeetCode】18. 4Sum 四数之和
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:four sum, 4sum, 四数之和,题解,leet ...
- 【LeetCode】18. 4Sum
题目: 思路:这题和15题很像,外层再加一个循环稍作修改即可 public class Solution { public List<List<Integer>> fourSu ...
- 【LeetCode】18、四数之和
题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...
- 【一天一道LeetCode】#18. 4Sum
一天一道LeetCode (一)题目 Given an array S of n integers, are there elements a, b, c, and d in S such that ...
- 【LeetCode】018 4Sum
题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...
- 【LeetCode】18.四数之和
题目描述 18. 四数之和 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 t ...
- 【LeetCode】454. 4Sum II 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcod ...
- 【LeetCode】16. 4Sum
题目:Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = ...
- 【LeetCode】46. Permutations (2 solutions)
Permutations Given a collection of numbers, return all possible permutations. For example,[1,2,3] ha ...
随机推荐
- sql递归查询子级
WITH T(emp_no, name, dept_no, the_level, path,path1,manager_id) AS( SELECT emp_no, name, dept_no ,1 ...
- easyui-datetimebox设置默认时分秒00:00:00
datetimebox默认打开面板显示的是当前的时间,有个需求就是当打开面板时显示固定的”00:00:00”时间, 它本身有个方法spinner方法可以获得时间微调器对象,它所依赖的组件combo有个 ...
- Coursera课程《大家的python》(Python for everyone)课件
You can access the Google Drive containing all of the current and in-progress lecture slides for thi ...
- 从原型模式(Prototype Pattern)到 Clone
前面提到抽象工厂的实现,这里说说抽象工厂的原型实现,与工厂方法的实现不同,原型实现有他自己的优点和缺点 原型的优点: 1. 效率:clone是native方法,比new的效率高,当使用复杂循环嵌套对象 ...
- @SpringContext通过实现ApplicationContextAware接口动态获取bean
场景: 在代码中需要动态获取spring管理的bean 目前遇到的主要有两种场景:1.在工具类中需要调用某一个Service完成某一个功能,如DictUtils2.在实现了Runnable接口的任务类 ...
- 用C语言获取任意文件的长度(可能大于2GB)
用C语言获取文件长度的常见思路是: 打开文件后用 fseek() 函数把文件位置指针移动到文件的末尾,用 ftell() 获得这时位置指针距文件头的字节数,这个字节数就是文件的长度.但是这样做也会受到 ...
- oauth2-server-php for windows 的那些坑 (研究中...)
oauth2-server-php for windows 的那些坑 在windwos 环境下,使用vs2017 for php 工具进行调试时,总是搞不出来, 于是分析了一下原因, 首先,oauth ...
- LuaCURL
LuaCURL:http://luacurl.luaforge.net/ curl大家应该都知道吧,在linux下被广泛使用,也有windows版本,网络上还有其win32版本的源代码.它是一个命令行 ...
- cocos lua 加密与解密 混淆 (版本号cocos3.4)
cocos luacompile cocos luacompile Overview Usage Available Arguments Samples Overview Compile the .l ...
- [每日一题] OCP1z0-047 :2013-08-24 FLASHBACK—TABLE/PRIMARY KEY(FOREIGN KEY?)......98
正确答案:D 根据题意如下操作: 一.创建表dept gyj@OCM> CREATE TABLE DEPT 2 (DEPTNO NUMBER(2,0), 3 DNAME VARCHAR2(14) ...