[array] leetCode-18. 4Sum -Medium
2024-08-27 23:54:07
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;
}
最新文章
- IntelliJ IDEA 绝对好用快捷键
- 在Linux(Ubuntu)下搭建ASP.NET Core环境并运行 继续跨平台
- [kipmi0]进程导致系统负载高
- JS 实现取整(二)
- 新版本的tlplayer for android ,TigerLeapMC for windows发布了
- Shell中的${},##和%%的使用
- Linux显示进程状态
- 软件开发顶尖高手的杀手锏SQL语句
- postgresql 删除库的时候报错database ";temp_test_yang"; is being accessed by other users
- Python3:判断三角形的类型
- EasyUI学习(一)——EasyUI入门
- 雪碧图和如何实现浏览器中title的小图标
- 解决GP服务产生的结果无法自动发布为地图服务的问题
- CSAPP lab2 二进制拆弹 binary bombs phase_5
- sql 防注入 维基百科
- 小型Http服务器
- 关于Oracle中的字符的比较
- 微信小程序-滑动视图注意事项
- f.lux Ubuntu 下进行安装
- Chart.js入门教程
热门文章
- Day5网络流
- OpenCV —— 矩阵操作
- 洛谷 P1709 [USACO5.5]隐藏口令Hidden Password
- Oracle数据库安装时 environment variable path 大于 1023
- jQuery过滤选择器具体解释
- git 工具的使用总结(6)-提交合并处理
- Linux 内存管理与系统架构设计
- 桌面版chrome调试APP的webview的步骤:
- BZOJ5137: [Usaco2017 Dec]Standing Out from the Herd(广义后缀自动机,Parent树)
- CISP/CISA 每日一题 12