leetcode18 四数之和 双指针
题外话:
这道题让我想起了
挑战程序设计竞赛有一个抽签问题,类似的a+b+c+d=target,可以重复使用一个数。
a+b+c+d=target转化为 a+b=target-c-d。 如果只是判断是否存在,那么可以预处理,得到所有c+d的值,然后binary_search (target-a-b)
处理方法
对于一个共有n个数的数组,准备一个数组int kk
kk[c*n+d]=k[c]+k[d]。
复杂度O(n^2log(n))

然后这道题:
就和前两个题差不多,先固定两个数,然后双指针法
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>>ret;
if(nums.empty())
return ret;
int len=nums.size();
if(len<4)
return ret;
sort(nums.begin(),nums.end());
for (int i = 0; i < len - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1])
continue;
for(int j=i+1;j<len-2;j++){
if(nums[j]==nums[j-1]&&(j>i+1))
continue;
int l = j + 1;
int r = len - 1;
while (l < r) { //多组
int s = nums[i] + nums[l] + nums[r]+nums[j];
if (s > target)
r--;
else if (s < target)
l++;
else {
ret.push_back({nums[i], nums[j],nums[l], nums[r]});
while (l < r && nums[l] == nums[++l]);
while (l < r && nums[r] == nums[--r]);
}
}
}
}
return ret;
}
};
leetcode18 四数之和 双指针的更多相关文章
- LeetCode18. 四数之和
LeetCode18. 四数之和 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值 ...
- Leetcode12. 整数转罗马数字Leetcode18. 四数之和
> 简洁易懂讲清原理,讲不清你来打我~ 输入整数,输出对应的罗马字符串 not null auto_i ...
- linux通过ntp同步时间
1.安装服务 yum install ntp ##安装ntp服务,这个和ntpdate不一样哦,用这个比较好 systemctl start ntpd.service ###启动服务 systemct ...
- javax.servlet.ServletException: No adapter for handler
问题描述: 我的web.xml如下: <?xml version="1.0" encoding="UTF-8"?> <web-app xmln ...
- CentOS 镜像下载地址
CentOS镜像地址:http://isoredirect.centos.org/altarch/7/isos/i386/
- Node 使用webpack编写简单的前端应用
编写目的 1. 使用 Node 依赖webpack.jQuery编写简单的前端应用. 操作步骤 (1)新建一个目录 $ mkdir simple-app-demo $ cd simple-app-de ...
- 知道 Redis-Cluster 么?说说其中可能不可用的情况
Redis 集群模式简述 一个集群模式的官方推荐最小最佳实践方案是 6 个节点,3 个 Master 3 个 Slave 的模式,如 图00 所示. key 分槽与转发机制 Redis 将键空间分为了 ...
- hbase 集群(完全分布式)方式安装
一,环境 1, 主节点一台: ubuntu desktop 16.04 zhoujun 172.16.12.1 从节点(slave)两台:ubuntu server 16.04 hadoo ...
- java HashMap and HashMultimap 区别
http://stackoverflow.com/questions/19222029/what-is-difference-between-hashmap-and-hashmultimap The ...
- java中的IO处理和使用,API详细介绍(二)
字符流 [向文件中写入数据] 现在我们使用字符流 /** * 字符流 * 写入数据 * */ import java.io.*; class hello{ public static void mai ...