18. 4Sum -Medium

descrition

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]
]

解析

与 3Sum 的思路一样。不过代码量一大要 bug free 还真得细心一些!!

code


#include <iostream>
#include <vector>
#include <algorithm>
#include <limits> using namespace std; class Solution{
public:
int threeSumClosest(vector<int>& nums, int target){
sort(nums.begin(), nums.end()); // ascending int min_gab = numeric_limits<int>::max();
int ans = target; for(int i=0; i<nums.size(); i++){
int target_local = target - nums[i];
int ileft = i + 1;
int iright = nums.size() - 1;
while(ileft < iright){ // two pointer searching
int sum = nums[ileft] + nums[iright];
if(sum == target_local) // right answer
return target;
if(sum < target_local) // move ileft to increase sum
ileft++;
else // sum > target_local
iright--; int gab = abs(sum - target_local);
if(gab < min_gab){
ans = sum + nums[i];
min_gab = gab;
}
}
} return ans; }
}; int main()
{
return 0;
}

最新文章

  1. IntelliJ IDEA 绝对好用快捷键
  2. 在Linux(Ubuntu)下搭建ASP.NET Core环境并运行 继续跨平台
  3. [kipmi0]进程导致系统负载高
  4. JS 实现取整(二)
  5. 新版本的tlplayer for android ,TigerLeapMC for windows发布了
  6. Shell中的${},##和%%的使用
  7. Linux显示进程状态
  8. 软件开发顶尖高手的杀手锏SQL语句
  9. postgresql 删除库的时候报错database &quot;temp_test_yang&quot; is being accessed by other users
  10. Python3:判断三角形的类型
  11. EasyUI学习(一)——EasyUI入门
  12. 雪碧图和如何实现浏览器中title的小图标
  13. 解决GP服务产生的结果无法自动发布为地图服务的问题
  14. CSAPP lab2 二进制拆弹 binary bombs phase_5
  15. sql 防注入 维基百科
  16. 小型Http服务器
  17. 关于Oracle中的字符的比较
  18. 微信小程序-滑动视图注意事项
  19. f.lux Ubuntu 下进行安装
  20. Chart.js入门教程

热门文章

  1. Day5网络流
  2. OpenCV —— 矩阵操作
  3. 洛谷 P1709 [USACO5.5]隐藏口令Hidden Password
  4. Oracle数据库安装时 environment variable path 大于 1023
  5. jQuery过滤选择器具体解释
  6. git 工具的使用总结(6)-提交合并处理
  7. Linux 内存管理与系统架构设计
  8. 桌面版chrome调试APP的webview的步骤:
  9. BZOJ5137: [Usaco2017 Dec]Standing Out from the Herd(广义后缀自动机,Parent树)
  10. CISP/CISA 每日一题 12