4Sum_leetCode
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)
N SUM和都是一个德性,代码例如以下:
class Solution
{
private:
vector<vector<int> > ret;
public:
vector<vector<int> > fourSum(vector<int> &num, int target)
{
sort(num.begin(), num.end()); ret.clear(); for(int i = 0; i < num.size(); i++)
{
if (i > 0 && num[i] == num[i-1])
continue; for(int j = i + 1; j < num.size(); j++)
{
if (j > i + 1 && num[j] == num[j-1])
continue; int k = j + 1;
int t = num.size() - 1; while(k < t)
{
if (k > j + 1 && num[k] == num[k-1])
{
k++;
continue;
} if (t < num.size() - 1 && num[t] == num[t+1])
{
t--;
continue;
} int sum = num[i] + num[j] + num[k] + num[t]; if (sum == target)
{
vector<int> a;
a.push_back(num[i]);
a.push_back(num[j]);
a.push_back(num[k]);
a.push_back(num[t]);
ret.push_back(a);
k++;
t--;
}
else if (sum < target)
k++;
else
t--;
}
}
} return ret;
}
};
4Sum_leetCode的更多相关文章
- 详谈Format String(格式化字符串)漏洞
格式化字符串漏洞由于目前编译器的默认禁止敏感格式控制符,而且容易通过代码审计中发现,所以此类漏洞极少出现,一直没有笔者本人的引起重视.最近捣鼓pwn题,遇上了不少,决定好好总结了一下. 格式化字符串漏 ...
随机推荐
- apache和tomcat群集
httpd.conf httpd.conf中添加: #与tomcat的插件 include "D:\clusterServer\apache\conf\mod_jk.con ...
- (转)Limboy:自学 iOS 开发的一些经验
不知不觉作为 iOS 开发也有两年多的时间了,记得当初看到 OC 的语法时,愣是被吓了回去,隔了好久才重新耐下心去啃一啃.啃了一阵,觉得大概有了点概念,看到 Cocoa 那么多的 Class,又懵了, ...
- db2字符串截取方法及常用函数
select substr(index_code, 1, locate('-', index_code)-1) from report_data substr(str,m,n)表示从str中的m个字符 ...
- [LOJ6208]树上询问
题目大意: 有一棵n节点的树,根为1号节点.每个节点有两个权值ki,ti,初始值均为0. 给出三种操作: 1.Add(x,d)操作:将x到根的路径上所有点的ki←ki+d 2.Mul(x,d)操作:将 ...
- NIO入门之BIO
传统BIO编程 网络编程的基本模型是Client-Server模型,也就是两个进程之间相互通信,其中服务端提供位置信息(绑定的IP地址和监听端口),客户端通过连接操作向服务端监听的端口发起连接请求,通 ...
- Bean的实例化--静态工厂
1,创建实体类User package com.songyan.demo1; /** * 要创建的对象类 * @author sy * */ public class User { private S ...
- SQL获取当月天数的几种方法
原文:SQL获取当月天数的几种方法 日期直接减去int类型的数字 等于 DATEADD(DAY,- 数字,日期) 下面三种方法: 1,日期加一个月减去当前天数,相当于这个月最后一天的日期.然后获取天数 ...
- hdoj 1159最长公共子序列
/*Common Subsequence A subsequence of a given sequence is the given sequence with some elements ( ...
- map以及iterator迭代器
https://www.cnblogs.com/fnlingnzb-learner/p/5833051.html https://www.cnblogs.com/hdk1993/p/4419779.h ...
- 使用websocket进行消息推送服务
Websocket主要做消息推送,简单,轻巧,比comet好用 入门了解:https://www.cnblogs.com/xdp-gacl/p/5193279.html /** * A Web Soc ...