4Sum

Given an array S of n integers, are there elements abc, 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.
  1. For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
  2.  
  3. A solution set is:
  4. (-1, 0, 0, 1)
  5. (-2, -1, 1, 2)
  6. (-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,不然会报错:

  1. error C2440: “类型转换”: 无法从“const std::vector<_Ty>”转换为“size_t

根据unordered_map的源码来看:

  1. // TEMPLATE CLASS hash
  2. template<class _Kty>
  3. class hash
  4. : public unary_function<_Kty, size_t>
  5. { // hash functor
  6. public:
  7. size_t operator()(const _Kty& _Keyval) const
  8. { // hash _Keyval to size_t value by pseudorandomizing transform
  9. ldiv_t _Qrem = _CSTD ldiv((long)(size_t)_Keyval, );
  10.  
  11. _Qrem.rem = * _Qrem.rem - * _Qrem.quot;
  12. if (_Qrem.rem < )
  13. _Qrem.rem += ;
  14. return ((size_t)_Qrem.rem);
  15. }
  16. };

key必须转换为size_t类型,对应于hash表下标。

保险起见,非内置类型就不要作为unordered_map的key了。

  1. class Solution {
  2. public:
  3. vector<vector<int> > fourSum(vector<int> &num, int target) {
  4. vector<vector<int> > result;
  5. if(num.empty() || num.size() < )
  6. return result;
  7. int size = num.size();
  8. sort(num.begin(), num.end());
  9. map<vector<int>, bool> m;
  10. for(int i = ; i < size-; i ++)
  11. {
  12. for(int j = i+; j < size-; j ++)
  13. {
  14. int k = j+; //k < size-1
  15. int l = size-;
  16. while(k < l)
  17. {
  18. int sum = num[i]+num[j]+num[k]+num[l];
  19. if(sum == target)
  20. {
  21. vector<int> cur(,);
  22. cur[] = num[i];
  23. cur[] = num[j];
  24. cur[] = num[k];
  25. cur[] = num[l];
  26. if(m.find(cur) == m.end())
  27. {
  28. result.push_back(cur);
  29. m[cur] = true;
  30. }
  31. k ++;
  32. l --;
  33. }
  34. else if(sum > target)
  35. l --;
  36. else
  37. k ++;
  38. }
  39. }
  40. }
  41. return result;
  42. }
  43. };

解法二:

不用开辟新的空间,通过跳过已访问过的元素来去重。

  1. class Solution {
  2. public:
  3. vector<vector<int> > fourSum(vector<int> &num, int target) {
  4. vector<vector<int> > ret;
  5. int size = num.size();
  6. sort(num.begin(), num.end());
  7. for(int i = ; i < size; i ++)
  8. {
  9. //skip same i
  10. while(i > && i < size && num[i] == num[i-])
  11. i ++;
  12. for(int j = i+; j < size; j ++)
  13. {
  14. //skip same j
  15. //attention: the first element (num[i+1]) should not be skipped
  16. while(j > i+ && j < size && num[j] == num[j-])
  17. j ++;
  18.  
  19. int k = j + ;
  20. int l = size - ;
  21. while(k < l)
  22. {
  23. int sum = num[i] + num[j] + num[k] + num[l];
  24. if(sum == target)
  25. {
  26. vector<int> cur();
  27. cur[] = num[i];
  28. cur[] = num[j];
  29. cur[] = num[k];
  30. cur[] = num[l];
  31. ret.push_back(cur);
  32. k ++;
  33. l --;
  34. //skip same k
  35. while(k < l && num[k] == num[k-])
  36. k ++;
  37. //skip same l
  38. while(l > k && num[l] == num[l+])
  39. l --;
  40. }
  41. else if(sum < target)
  42. {
  43. k ++;
  44. //skip same k
  45. while(k < l && num[k] == num[k-])
  46. k ++;
  47. }
  48. else
  49. {
  50. l --;
  51. //skip same l
  52. while(l > k && num[l] == num[l+])
  53. l --;
  54. }
  55. }
  56. }
  57. }
  58. return ret;
  59. }
  60. };

【LeetCode】18. 4Sum (2 solutions)的更多相关文章

  1. 【LeetCode】18. 4Sum 四数之和

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:four sum, 4sum, 四数之和,题解,leet ...

  2. 【LeetCode】18. 4Sum

    题目: 思路:这题和15题很像,外层再加一个循环稍作修改即可 public class Solution { public List<List<Integer>> fourSu ...

  3. 【LeetCode】18、四数之和

    题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...

  4. 【一天一道LeetCode】#18. 4Sum

    一天一道LeetCode (一)题目 Given an array S of n integers, are there elements a, b, c, and d in S such that ...

  5. 【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 = ...

  6. 【LeetCode】18.四数之和

    题目描述 18. 四数之和 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 t ...

  7. 【LeetCode】454. 4Sum II 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 字典 日期 题目地址:https://leetcod ...

  8. 【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 = ...

  9. 【LeetCode】46. Permutations (2 solutions)

    Permutations Given a collection of numbers, return all possible permutations. For example,[1,2,3] ha ...

随机推荐

  1. [MAC OS] NSOpenPanel 使用

    Mac OS开启沙盒之后,文件的保存会涉及到一个权限问题.如下图,在Capabilities中,可以勾选的权限一共有5种. User Selected File 必须勾选,否则 NSOpenPanel ...

  2. Snail—Hibernate反向生成实体类及配置文件

    今天学习了Hibernate的反向生成类文件 第一步.打开myeclipse中的database视图,找到对应的表,选中后右键单击. watermark/2/text/aHR0cDovL2Jsb2cu ...

  3. 第十二章 springboot + mongodb(复杂查询)

    简单查询:使用自定义的XxxRepository接口即可.(见 第十一章 springboot + mongodb(简单查询)) 复杂查询:使用MongoTemplate以及一些查询条件构建类(Bas ...

  4. go语言之进阶篇同名字段

    1.同名字段 示例: package main import "fmt" type Person struct { name string //名字 sex byte //性别, ...

  5. 什么是ScaleIO中的forwards rebuild和backwards rebuild?

    Forward rebuild发生在磁盘或节点挂掉的时候. 这种rebuild的过程的load是均衡到protection domain中所有可用的磁盘和节点上的. 这种rebuild相对于backw ...

  6. Unable to find manifest signing certificate in the certificate store

    方法一:把DEF项目的属性->Signing选项->Sign the ClickOnce manifests 勾去掉,这样就可以编绎通过了: 方法二:用记事本打开 *.csproj文件 , ...

  7. 关于opacity的思考

    今天在封装图片轮播的插件的时候,产生了这个opacity的小小思考. 我这个轮播的思路不是以前baidu输入法官网的设置外层容器overflow为hidden,position为relative用se ...

  8. Cognos启用第三方邮件服务代发功能

    很早之前已经说过如何利用cognos计划表定时发送报告给其他邮箱,今天由于第三方的邮箱策略发生了些许的改变,就再来说一下,以网易邮箱为例 如上图所示,如果Cognos要启用网易163作为代理,那么我们 ...

  9. VC操作MPP文件

    1.背景简介 因需要对Office系列进行程序操作,特需要使用COM编程. Microsoft Project生成进度计划,office家族软件,文件后缀为.mpp. 具体信息见维基百科http:// ...

  10. js生成pdf报表

    由于前台html已经动态生成报表,而且,前台有一个功能,一个date range组件,当你拖动的时候,报表会在不提交到后台的情况下动态变化.因此需要用到js生成生报表: 用到的组件: jquery.j ...