博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode 4Sum
阅读量:4703 次
发布时间:2019-06-10

本文共 1580 字,大约阅读时间需要 5 分钟。

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.

 

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一样
class Solution {public:    vector
> fourSum(vector
&num, int target) { vector
> res; int n = num.size(); if( n < 4) return res; sort(num.begin(),num.end()); for(int i = 0; i < n-3; ++ i){ if(i !=0 && num[i]== num[i-1]) continue; for(int j = i+1; j < n-2; ++ j){ if(j!=i+1 && num[j] == num[j-1] ) continue; int start = j+1, end = n-1; while(start < end){ int sum = num[i]+num[j]+num[start]+num[end]; if(sum > target) end--; else if(sum < target) start++; else{ vector
a; a.push_back(num[i]);a.push_back(num[j]); a.push_back(num[start]);a.push_back(num[end]); res.push_back(a); do{start++;}while(start < end && num[start] == num[start-1]); do{end--;}while(start < end && num[end] == num[end+1]); } } } } return res; }};
 

 

 

转载于:https://www.cnblogs.com/xiongqiangcs/p/3824058.html

你可能感兴趣的文章
Partial Tree UVALive - 7190(完全背包)
查看>>
『深度应用』NLP机器翻译深度学习实战课程·零(基础概念)
查看>>
『深度应用』NLP命名实体识别(NER)开源实战教程
查看>>
『深度应用』NLP机器翻译深度学习实战课程·壹(RNN base)
查看>>
『深度应用』一小时教你上手MaskRCNN·Keras开源实战(Windows&Linux)
查看>>
『王霸之路』从0.1到2.0一文看尽TensorFlow奋斗史
查看>>
查看客户端的IP地址,机器名,MAC地址,登陆名等信息
查看>>
MySQL常用函数
查看>>
Ubuntu安装搜狗拼音教程
查看>>
Happy Number
查看>>
Sqlserver 系统视图简单说明
查看>>
【摘录】PHP异步调用实现方式
查看>>
php缓存机制
查看>>
bzoj2049 线段树 + 可撤销并查集
查看>>
sql语句---存在即更新,否则insert
查看>>
cookie机制、session机制
查看>>
BZOJ 3787: Gty的文艺妹子序列
查看>>
Comet OJ - Contest #5 简要题解
查看>>
CF1093G Multidimensional Queries
查看>>
移动端提升页面速度与网站性能
查看>>