【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 ...
随机推荐
- 郑捷2017年电子工业出版社出版的图书《NLP汉语自然语言处理原理与实践》
郑捷2017年电子工业出版社出版的图书<NLP汉语自然语言处理原理与实践> 第1章 中文语言的机器处理 1 1.1 历史回顾 2 1.1.1 从科幻到现实 2 1.1.2 早期的探索 3 ...
- 2012年及之后的ImageNet比赛的冠军、亚军和季军ImageNet winners after 2012
2012 0.15 - Supervision (AlexNet) - ~ 60954656 params 0.26 - ISI (ensemble of features) 0.27 - LEAR ...
- MICS:副本和纠删码混合存储系统
摘要 云存储系统的三个指标: 高可靠性,低存储开销,高读写性能. 这三个指标是没有办法同一时候满足的,许多时候须要进行tradeoff. 副本系统和纠删码是两种在存储系统中广泛使用的策略,它们在保证高 ...
- MySQL对索引的使用
什么是索引 使用索引可快速访问数据库表中的特定信息.索引是对数据库表中一列或多列的值进行排序的一种结构,例如 order 表的订单号(orderNum)列.如果要按订单号查找特定订单,与必须搜索表中的 ...
- UVA 156 (13.08.04)
Ananagrams Most crossword puzzle fans are used to anagrams--groupsof words with the same letters i ...
- Ubuntu Linux自动发邮件配置及邮件发送脚本
测试环境:Ubuntu 11.10 1. 安装mutt及msmtp软件 sudo apt-get install mutt sudo apt-get install msmtp 2. 编辑配置文件vi ...
- mybatis异常 :元素内容必须由格式正确的字符数据或标记组成。
今天同事写一个查询接口的时候,出错:元素内容必须由格式正确的字符数据或标记组成. 错误原因:mybatis查询的时候,需要用到运算符 小于号:< 和 大于号: >,在mybatis配置文 ...
- docker 基本原理及快速入门
作者地址:青牛 什么是docker Docker 是一个开源项目,诞生于 2013 年初,最初是 dotCloud 公司内部的一个业余项目.它基于 Google 公司推出的 Go 语言实现. 项目后来 ...
- 同一页面的两个Iframe,其中一个iframe获取另一个iframe内的iframe中的元素值
公共父页面(主页面): <%@ page language="java" import="java.util.*" pageEncoding=" ...
- IOS实现多媒体音频之音乐播放器
随着智能手机市场越来越活跃,相应的app也变得五彩缤纷,各式各样,让你的app更吸引人多媒体技术不可避免.通过对音频和视频等控制让你的app更加丰富多彩,今天和大家一起研究下基本的音频使用.本文只提供 ...