当前位置: 首页 > 编程日记 > 正文

Leetcode | 3Sum

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)

主要在去重方面走了弯路。思路同Two sum.

从num中取出一个数,就要把它的所有和为0的组合找出来。

找到一组之后,找下一组,i++,j--,但是要注意去重。

取出一个数的时候,就从它后面开始找其他两个数,因为在他之间的数已经找过了。 i = k + 1;

确定范围之后,下一个k必须要忽略相同的数(Line 12) num[k] != num[k+1],k++。

 1     vector<vector<int> > threeSum(vector<int> &num) {
 2         vector<vector<int> > ret;
 3         if (num.size() < 3) return ret;
 4         
 5         vector<int> v;
 6         sort(num.begin(), num.end());
 7         
 8         for (int k = 0; k < num.size(); ++k) {
 9             // get num[k], search in [k + 1, n - 1]
10             int i = k + 1, j = num.size() - 1;
11             
12             // ignore duplicate num[k]
13             while (k < num.size() - 1 && num[k] == num[k + 1]) k++;
14             
15             while (j > i) {
16                 int s = num[i] + num[j];
17 
18                 if (s == -num[k]) {
19                     v.push_back(num[i]);
20                     v.push_back(num[k]);
21                     v.push_back(num[j]);
22                     sort(v.begin(), v.end());
23                     ret.push_back(v);
24                     v.clear();
25                     
26                     // continue to find another match
27                     i++;
28                     while (i <= j && num[i] == num[i - 1]) i++;
29                     j--;
30                     while (j >= i && num[j] == num[j + 1]) j--;
31                 } else if (s > -num[k]) {
32                     j--;
33                 } else {
34                     i++;
35                 }
36             }
37         }
38         
39         return ret;
40     }

写得简洁一点。

 1 class Solution {
 2 public:
 3     vector<vector<int> > threeSum(vector<int> &num) {
 4         vector<vector<int> > ans;
 5         if (num.empty()) return ans;
 6         sort(num.begin(), num.end());
 7         int n = num.size();
 8         for (int i = 0; i + 2 < n; ) {
 9             int target = -num[i]; 
10             for (int j = i + 1, k = n - 1; j < k; ) {
11                 int sum = num[j] + num[k];
12                 if (sum == target) { // sum + num[i] == 0
13                     vector<int> tmp = {num[i], num[j], num[k]};
14                     sort(tmp.begin(), tmp.end());
15                     ans.push_back(tmp);
16                     for (++j; j < k && num[j] == num[j - 1]; ++j); // ignore dups
17                     for (--k; k > j && num[k] == num[k + 1]; --k);
18                 } else if (sum < target) {
19                     j++;
20                 } else {
21                     k--;
22                 }
23             }
24             for (++i; i + 2 < n && num[i] == num[i - 1]; ++i);
25         }
26         
27         return ans;
28     }
29 };

3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

For example, given array S = {-1 2 1 -4}, and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

和3 sum类似,就是在查找的时候,必须跟踪最小的差值。

 1 class Solution {
 2 public:
 3     int threeSumClosest(vector<int> &num, int target) {
 4         if (num.size() < 3) return INT_MAX;
 5         
 6         sort(num.begin(), num.end());
 7         int minDiff = INT_MAX, minSum = target;
 8         for (int k = 0; k < num.size(); ++k) {
 9             // get num[k], search in [k + 1, n - 1]
10             int i = k + 1, j = num.size() - 1;
11             
12             int t = target - num[k]; 
13             
14             while (j > i) {
15                 int s = num[i] + num[j];
16                 if (abs(s - t) < minDiff) {
17                     minDiff = abs(s - t);
18                     minSum = s + num[k];
19                 }
20                 if (s == t) {
21                     return target;
22                 } else if (s > t) {
23                     j--;
24                 } else {
25                     i++;
26                 }
27             }
28             
29             // ignore duplicate num[k]
30             while (k < num.size() - 1 && num[k] == num[k + 1]) k++;
31         }
32         
33         return minSum;
34     }
35 };

4Sum

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)

3 sum类似,加了一层。244ms.

 1 class Solution {
 2 public:
 3     vector<vector<int> > fourSum(vector<int> &num, int target) {
 4         vector<vector<int> > ret;
 5         if (num.size() < 4) return ret;
 6         
 7         vector<int> v;
 8         sort(num.begin(), num.end());
 9         
10         for (int m = 0; m < num.size(); ++m) {
11             for (int k = m + 1; k < num.size(); ++k) {
12                 // get num[k], search in [k + 1, n - 1]
13                 int i = k + 1, j = num.size() - 1;
14                 int t = target - num[m] - num[k];
15                 // ignore duplicate num[k]
16                 while (k < num.size() - 1 && num[k] == num[k + 1]) k++;
17                 
18                 while (j > i) {
19                     int s = num[i] + num[j];
20     
21                     if (s == t) {
22                         v.push_back(num[m]);
23                         v.push_back(num[k]);
24                         v.push_back(num[i]);
25                         v.push_back(num[j]);
26                         sort(v.begin(), v.end());
27                         ret.push_back(v);
28                         v.clear();
29                         
30                         // continue to find another match
31                         i++;
32                         while (i <= j && num[i] == num[i - 1]) i++;
33                         j--;
34                         while (j >= i && num[j] == num[j + 1]) j--;
35                     } else if (s > t) {
36                         j--;
37                     } else {
38                         i++;
39                     }
40                 }
41             }
42             while (m < num.size() - 1 && num[m] == num[m + 1]) m++;
43         }
44         return ret;
45     }
46 };

4 sum有O(n^2)的解法,leetcode的discuss后面有。但是那个代码760ms。按照同样的思路,用set来去重,也是760ms。

 1 class Solution {
 2 public:
 3     vector<vector<int> > fourSum(vector<int> &num, int target) {
 4         vector<vector<int> > ret;
 5         if (num.size() < 4) return ret;
 6         
 7         sort(num.begin(), num.end());
 8         
 9         map<int, vector<pair<int, int> > > sums;
10         
11         for (int i = 0; i < num.size(); ++i) {
12             for (int j = i + 1; j < num.size(); ++j) {
13                 sums[num[i] + num[j]].push_back(pair<int, int>(i, j));
14             }
15         }
16         
17         map<int, vector<pair<int, int> > >::iterator it;
18         vector<int> v;
19         set<vector<int> > r;
20         for (int i = 0; i < num.size(); ++i) {
21             for (int j = i + 1; j < num.size(); ++j) {
22                 int s = target - num[i] - num[j];
23                 if ((it = sums.find(s)) != sums.end()) {
24                     for (vector<pair<int, int>>::iterator it2 = it->second.begin(); 
25                             it2 != it->second.end(); ++it2) {
26                         if (it2->first <= j) continue;
27                         v.push_back(num[i]);
28                         v.push_back(num[j]);
29                         v.push_back(num[it2->first]);
30                         v.push_back(num[it2->second]);
31                         r.insert(v);
32                         v.clear();
33                     }
34                 }
35             }
36         }
37         
38         for (set<vector<int> >::iterator it = r.begin(); it != r.end(); it++) {
39             ret.push_back(*it);
40         }
41         return ret;
42     }
43 };

转载于:https://www.cnblogs.com/linyx/p/3716788.html

相关文章:

玩转 JavaScript 面试:何为函数式编程?

函数式编程在 JavaScript 领域着实已经成为一个热门话题。就在几年前&#xff0c;很多 JavaScript 程序员甚至都不知道啥是函数式编程&#xff0c;但是就在近三年里我看到过的每一个大型应用的代码库中都包含了函数式编程思想的大规模使用。 函数式编程(缩写为 FP)是一种通过组…

正则表达式分类 区别

原文地址&#xff1a;http://www.cnblogs.com/chengmo/archive/2010/10/10/1847287.html 正则表达式&#xff1a;在计算机科学中&#xff0c;是指一个用来描述或者匹配一系列符合某个句法规则的字符串的单个字符串。在很多文本编辑器或其他工具里&#xff0c;正则表达式通常被用…

Java项目:嘟嘟校园一卡通系统(java+JSP+Servlet+html+css+JavaScript+JQuery+Ajax+mysql)

源码获取&#xff1a;博客首页 "资源" 里下载&#xff01; 一、项目简述 功能&#xff1a;卡管理&#xff0c;卡消费&#xff0c;卡充值&#xff0c;图书借阅&#xff0c;消费&#xff0c;记录&#xff0c;注销等等功能。 二、项目运行 环境配置&#xff1a; Jdk…

OC与C语言的区别

C语言是面向过程的编程语言&#xff0c;而OC则是面向对象的编程语言。面向对象:打个比方,就是你做一次菜,让老婆做个菜,吃饭,这就是面向对象,效率高面向过程,就是每一个细节:比如你要先把或开到合适的位置.然后还要洗菜 ,等油热了,才能开始炒菜,然后调料,...,起锅,到碗里,吃饭.…

Hutool之集合工具——CollectionUtil

为什么80%的码农都做不了架构师&#xff1f;>>> 集合工具 CollectionUtil 这个工具主要增加了对数组、集合类的操作。 1. join 方法 将集合转换为字符串&#xff0c;这个方法还是挺常用&#xff0c;是StrUtil.split的反方法。这个方法的参数支持各种类型对象的集合…

15:解决IntelliJ IDEA的乱码问题

1. -Dfile-encodingsUTF-8 &#xff0c;全局&#xff1a; 转载于:https://www.cnblogs.com/gzhbk/p/10991335.html

C++ 和C 语言混合代码导致的问题

C语言中操作字符串用C运行时函数&#xff1a;strtok, strcmp, strcpy等等&#xff0c;直接操作内存。在c引入的字符串操作类std:string &#xff0c;string类中必有一个私有成员&#xff0c;其是一个char*&#xff0c;用户记录从堆上分配内存的地址&#xff0c;其在构造时分配内…

SVN详细使用教程

SVN简介&#xff1a; 为什么要使用SVN&#xff1f; 程序员在编写程序的过程中&#xff0c;每个程序员都会生成很多不同的版本&#xff0c;这就需要程序员有效的管理代码&#xff0c;在需要的时候可以迅速&#xff0c;准确取出相应的版本。 Subversion是什么&#xff1f; 它是一…

Java项目:药店信息管理系统(java+SSM+JSP+layui+maven+mysql)

源码获取&#xff1a;博客首页 "资源" 里下载&#xff01; 一、项目简述 环境配置&#xff1a; Jdk1.8 Tomcat8.5 mysql Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09; 项目技术&#xff1a; JSP Spring SpringMVC MyBatis ht…

MongoDB简单操作

MongoDB简单操作 Hadoop核心技术厂商Cloudera将在2014/06推出hadoop Ecosystem与MongoDB的整合产品,届时MongoDB与ipmala及hbase,hive一起用; 开源linux领军企业RHEL也宣布RHEL将整合MongoDB用于简化用户账号管理与LDAP一起用; 数据仓库之MPP技术 领军者莫非 Vertica,exterdata…

Windows Presentation Foundation(介绍外连接)

Windows Presentation Foundation 2011/08/12更新&#xff1a;2010 年 12 月 Windows Presentation Foundation (WPF) 为开发人员提供了统一的编程模型&#xff0c;可用于构建合并了 UI、媒体和文档的丰富 Windows 智能客户端用户体验。 欢迎使用 WPF 了解 WPF&#xff1a; WP…

Linux中与进程终止相关的信号SIGTERM,SIGKILL,SIGINT

1. SIGTERM “kill pid” 会发送SIGTERM到进程pid. This is the termination signal sent by killcommand by default. 2. SIGINT 在终端中敲入interrupt key&#xff08;DELETE或ctrlc&#xff09;会产生SIGINT信号。这个信号会被发送到进程(inforeground proc…

Java项目:嘟嘟二手书商城系统(java+JSP+Springboot+maven+mysql+ThymeLeaf+FTP)

源码获取&#xff1a;博客首页 "资源" 里下载&#xff01; 一、项目简述 功能&#xff1a; 主页显示商品&#xff1b; 所有二手书商品展示&#xff0c;可进行商品搜索&#xff1b; 点击商品进入商品详情页&#xff0c;具有立即购买和加入购物车功能&#xff0c;可增减…

SQL用法总结

1、创建数据库语句 create table persons(id INT NOT NULL AUTO_INCREMENT,lastname VARCHAR(255) NOT NULL,firstname VARCHAR(255) NOT NULL,PRIMARY KEY (ID)) DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; 2、创建数据库时&#xff0c;PK、NN、UQ、BIN、UN、…

[leetcode] Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes values. For example:Given binary tree {1,#,2,3}, 1\2/3return [1,2,3]. Note: Recursive solution is trivial, could you do it iteratively? 给定一棵二叉树&#xff0c;使用非递归的方法进行先序遍历。…

error C2065: “M_PI”: 未声明的标识符

1.首先&#xff0c;程序中头文件的选择&#xff0c;要选择<math.h>头文件&#xff0c;在<cmath>文件中是没有对M_PI 的定义的&#xff08;现在的<cmath>中对M_PI好像已有定义&#xff09;。2.选择&#xff1a;项目——>”XXX属性"——>配置属性—…

区分HPUX是Itanium还是PA-RISC

转自&#xff1a;http://blog.csdn.net/nbzll0920/article/details/7961232 pa-risc的产品号以rp打头&#xff0c;itanium的产品号以rx打头 用model或者uname -a命令看一下就知道了 PS: Intel安腾处理器构建在IA-64&#xff08;Intel Architecture 64&#xff09;&#xff0c;…

Java项目:食品溯源系统(java+Springboot+Maven+mybatis+Vue+mysql+wd)

源码获取&#xff1a;博客首页 "资源" 里下载&#xff01; 一、项目运行 环境配置&#xff1a; Jdk1.8 Tomcat8.5 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术…

使用sqlite保存数据返回主键

/// <summary>/// 返回insert后的主键值/// </summary>/// <param name"SQLString"></param>/// <param name"para"></param>/// <returns></returns>public static int ExecuteSql(string SQLString, Li…

Pycharm初始创建项目和环境搭建(解决aconda库文件引入不全等问题)

1.新建工程 1&#xff0e;选择新建一个Pure Python项目&#xff0c;新建项目路径可以在Location处选择。 2.Project Interpreter部分是选择新建项目所依赖的python库&#xff0c;第一个选项会在项目中简历一个venv&#xff08;virtualenv&#xff09;目录&#xff0c;这里存放…

Java项目:宠物商城系统(java+Springboot+Maven+mybatis+Vue+mysql)

源码获取&#xff1a;博客首页 "资源" 里下载&#xff01; 一、项目运行 环境配置&#xff1a; Jdk1.8 Tomcat8.5 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术…

android插件化-apkplug中以监听方式获取OSGI服务-09

2019独角兽企业重金招聘Python工程师标准>>> 我们提供 apkplug 下OSGI使用demo 源码托管地址为 http://git.oschina.net/plug/OSGIService 一 需求 通过 <<apkplug中OSGI服务基本原理-08>>我们知道怎样注册于查询OSGI Service。但查询方式必须在Servi…

网页失去焦点事件 visibilitychange

当网页失去焦点事件时会触发 visibilitychange 事件&#xff0c;可进行相关逻辑处理 如失去焦点需暂停播放 或 变更title吸引用户回来.. eg: <script>document.addEventListener(visibilitychange, function () {var isHidden document.hidden;if (isHidden) {//失去焦点…

UML类图符号 各种关系说明以及举例

UML中描述对象和类之间相互关系的方式包括&#xff1a;依赖&#xff08;Dependency&#xff09;&#xff0c;关联&#xff08;Association&#xff09;&#xff0c;聚合&#xff08;Aggregation&#xff09;&#xff0c;组合&#xff08;Composition&#xff09;&#xff0c;泛…

Java项目:医院预约挂号系统(java+SpringBoot+Maven+Vue+mysql)

源码获取&#xff1a;博客首页 "资源" 里下载&#xff01; 一、项目运行 环境配置&#xff1a; Jdk1.8 Tomcat8.5 Mysql HBuilderX&#xff08;Webstorm也行&#xff09; Eclispe&#xff08;IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持&#xff09;。 项目技术…

《暗时间》读后感

什么是暗时间 什么是暗时间&#xff1f;你走路、买菜、洗脸洗手、坐公车、逛街、出游、吃饭、睡觉&#xff0c;所有这些时间都可以称为“暗时间”。我理解暗时间就是把自己平时在不知不觉中度过的&#xff0c;看不到它流逝的时光充分利用起来的时间。这些时间在作者的眼里是可以…

AbstractMap详解

/ 包:java.util// 包:java.util package java . util;Map.Entry;​同 SimpleEntry 一样,都继承了 Map.Entry 和 序列化接口。

OpenGL渲染流水中的处理步骤

显示列表:不管数据描述的是几何体还是像素,都可以被存储在显示列表中,供现在或以后使用;也可以不将数据存储在显示列表中,而是立刻对数据进行处理,这被称为直接模式.显示列表被执行时,其中存储的数据被发送出去,就像在应用程序中用直接模式发送一样.求值程序:所有的几何图元最终…

需要在method方法被调用之后,仅打印出a=100,b=200,请写出method方法的代码

通常,此流对应于显示器输出或者由主机环境或用户指定的另一个输出目标。通常,此流对应于键盘输入或者由主机环境或用户指定的另一个输入源。public static final PrintStream err“标准”错误输出流。PrintStream 是打印输出流,它继承于FilterOutputStream。第二个用的是用的是char类型,根本不是方法,当要输出方法体的时候,会给你遍历数组。通常,此流对应于显示器输出或者由主机环境或用户指定的另一个输出目标。诡异的是,如果错了,面试官对你说了一句:你回去看看,

Linux复制文件scp

cp 复制文件(copy) cp sourcefile destfile scp 跨服务器复制(secure copy) (1) 复制文件&#xff1a; scp local_file remote_usernameremote_ip:remote_folder 或 scp local_file remote_usernameremote_ip:remote_file 或 scp local_file remote_ip:remote_folder 或 scp lo…