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: 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]
]
关于这个问题,我最初的想法很简单,就是暴力搜索所有数值,然后得到所有的和为0的子序列。但是这个做法的问题是会得到重复的序列,那么思考下去就是,判断得到的子序列是否与前面已经存下来的数据重复,如果重复则不存。
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> > threeSum(vector<int>& nums);
bool compare(vector<int> &v1, vector<int>& v2);
vector<vector<int> > threeSum(vector<int>& nums) {
vector< vector<int> >ret;
if (nums.size() < 3) {
return ret;
}
int size = nums.size();
for (vector<int>::const_iterator it = nums.cbegin(); it != (nums.cend() - 2); it++) {
int first = *it;
for (vector<int>::const_iterator it2 = it + 1; it2 != (nums.end() - 1); it2++) {
int second = *it2;
for (vector<int>::const_iterator it3 = it2 + 1; it3 != nums.end(); it3++) {
if (*it3 + second + first) {
continue;
} else {
vector<int> tmp;
tmp.push_back(first);
tmp.push_back(second);
tmp.push_back(*it3);
bool dump = false;
for (vector<vector<int> >::iterator itt = ret.begin(); itt != ret.end(); itt++) {
if (compare(tmp, *itt)) {
dump = true;
break;
}
}
if (dump) {
continue;
}
ret.push_back(tmp);
cout<< *it3 << second << first <<endl;
}
}
}
}
return ret;
}
bool compare(vector<int> &v1, vector<int>& v2) {
for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) {
bool ret = false;
for (vector<int>::iterator it2 = v2.begin(); it2 != v2.end(); it2++) {
if (*it == *it2) {
// cout<<*it2<<endl;
v2.erase(it2);
// cout<<*it2<<endl;
ret = true;
break;
}
}
if (!ret) {
return false;
}
}
return true;
}
这一坨玩意儿实际上是可行的,但是运行超时了,时间复杂度>O(n^5) 基本就是一坨垃圾了。
考虑新的计算方法,在计算中就规避掉会导致重复的情况。经过思考,重复的序列和重复的数字是有关系的,即当已经使用过某一个数字,来搜索剩余两个数字,如果后面这个数字再次出现,那么就不必要再搜索一次了,搜索的结果就是重复的结果,是无意义的。
为了使计算方便,首先做个排序,然后依次判断,如果重复出现就不再计算,这样下来时间复杂度降到了O(n^3)
Runtime: 139 ms
Your runtime beats 1.36% of cpp submissions.
还是很可怜的成绩,需要继续优化。
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> > threeSum(vector<int>& nums);
void sortv(vector<int> &vec);
vector<vector<int> > threeSum(vector<int>& nums) {
vector< vector<int> >ret;
if (nums.size() < 2) {
return ret;
}
if (nums.size() == 3) {
if (nums[1] + nums[2] + nums[0] == 0) {
ret.push_back(nums);
}
return ret;
}
sortv(nums);
int size = nums.size();
int last_1;
int last_2;
int last_3;
for (vector<int>::const_iterator it = nums.cbegin(); it != (nums.cend() - 2); it++) {
int first = *it;
// cout<<"first and last_1"<<first<<last_1<<endl;
if (it != nums.cbegin()) {
if (first == last_1) {
// cout<<"same first"<<first<<endl;
continue;
}
}
last_1 = first;
// 2rd Loop
for (vector<int>::const_iterator it2 = it + 1; it2 != (nums.end() - 1); it2++) {
int second = *it2;
// cout<<"No.2 for loop: "<<(*it2)<<" last2: "<<last_2<<endl;
if (it2 != it + 1) {
if (second == last_2) {
// cout<<"same second"<<second<<endl;
continue;
}
}
last_2 = second;
// Third loop
for (vector<int>::const_iterator it3 = it2 + 1; it3 != nums.end(); it3++) {
int third = *it3;
if (it3 != it2 + 1) {
if (third == last_3) {
// cout<<"same third"<<third<<endl;
continue;
}
}
last_3 = third;
if (*it3 + second + first) {
continue;
} else {
vector<int> tmp;
tmp.push_back(first);
tmp.push_back(second);
tmp.push_back(*it3);
ret.push_back(tmp);
// cout<< *it3 << second << first <<endl;
}
}
}
}
return ret;
}
void sortv(vector<int> &vec) {
for (int i = vec.size(); i > 0; --i) {
for (int j = 0; j < i - 1; ++j) {
if (vec[j] > vec[j + 1]) {
int t = vec[j];
vec[j] = vec[j + 1];
vec[j + 1] = t;
}
}
}
// for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
// cout<<"Sort:"<<(*it)<<endl;
// }
}
果然自己脑子还是不够用,上网查了一下人家的解法,复杂度直接降到O(n^2).具体代码可见: 九章 - 3Sum 人家如何减少一个量级的复杂度呢?将数组排序以后,首先一个完整的循环,nums[i],那么我们需要的另两个数的和就应该是 -nums[i]. 现在有两个游标,一个从头,一个从尾。因为无论如何不可能三个数值都为正或者都负,肯定是一个更靠近头部,一个更靠近尾部。如果求得的和比我们要的小,说明起点太小,往前面挪一个,反则往后挪。主要在搜寻中遇到重复的数据也一样把他去除掉。
class Solution {
public:
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
vector<vector<int> > threeSum(vector<int> &nums) {
vector<vector<int> > result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// two sum;
int start = i + 1, end = nums.size() - 1;
int target = -nums[i];
while (start < end) {
if (start > i + 1 && nums[start - 1] == nums[start]) {
start++;
continue;
}
if (nums[start] + nums[end] < target) {
start++;
} else if (nums[start] + nums[end] > target) {
end--;
} else {
vector<int> triple;
triple.push_back(nums[i]);
triple.push_back(nums[start]);
triple.push_back(nums[end]);
result.push_back(triple);
start++;
}
}
}
return result;
}
};
LeetCode: 3Sum的更多相关文章
- [LeetCode] 3Sum Smaller 三数之和较小值
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...
- [LeetCode] 3Sum Closest 最近三数之和
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
- [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 un ...
- LeetCode 3Sum Smaller
原题链接在这里:https://leetcode.com/problems/3sum-smaller/ 题目: Given an array of n integers nums and a targ ...
- leetcode — 3sum
import java.util.*; /** * Source : https://oj.leetcode.com/problems/3sum/ * * Created by lverpeng on ...
- LeetCode:3Sum, 3Sum Closest, 4Sum
3Sum Closest Given an array S of n integers, find three integers in S such that the sum is closest t ...
- Leetcode 3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...
- leetcode—3sum
1.题目描述 Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find ...
- Leetcode 3Sum Closet
二手和3Sum像几乎相同的想法.二进制搜索.关键修剪.但是,在修剪做出很多错误. 然后还有一个更加速了原来的想法O(n^2). #include<iostream> #include &l ...
随机推荐
- NuGet镜像上线试运行
为解决国内访问NuGet服务器速度不稳定的问题,我们用阿里云服务器搭建了一个NuGet镜像,目前已上线试运行. 使用NuGet镜像源的方法如下: 1)NuGet镜像源地址:https://nuget. ...
- Microsoft Loves Linux
微软新任CEO纳德拉提出的“Microsoft Loves Linux”,并且微软宣布.NET框架的开源,近期Microsoft不但宣布了Linux平台的SQL Server,还宣布了Microsof ...
- C# 利用性能计数器监控网络状态
本例是利用C#中的性能计数器(PerformanceCounter)监控网络的状态.并能够直观的展现出来 涉及到的知识点: PerformanceCounter,表示 Windows NT 性能计数器 ...
- PHP-会员登录与注册例子解析-学习笔记
1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...
- 基于netty http协议栈的轻量级流程控制组件的实现
今儿个是冬至,所谓“冬大过年”,公司也应景五点钟就放大伙儿回家吃饺子喝羊肉汤了,而我本着极高的职业素养依然坚持留在公司(实则因为没饺子吃没羊肉汤喝,只能呆公司吃食堂……).趁着这一个多小时的时间,想跟 ...
- javascript匹配各种括号书写是否正确
今天在codewars上做了一道题,如下 看上去就是验证三种括号各种嵌套是否正确书写,本来一头雾水,一种括号很容易判断, 但是三种怎么判断! 本人只是个前端菜鸟,,不会什么高深的正则之类的. 于是,在 ...
- kafka源码分析之一server启动分析
0. 关键概念 关键概念 Concepts Function Topic 用于划分Message的逻辑概念,一个Topic可以分布在多个Broker上. Partition 是Kafka中横向扩展和一 ...
- [转载]SQL Server 2008 R2安装时选择的是windows身份验证,未选择混合身份验证的解决办法
安装过程中,SQL Server 数据库引擎设置为 Windows 身份验证模式或 SQL Server 和 Windows 身份验证模式.本文介绍如何在安装后更改安全模式. 如果在安装过程中选择&q ...
- 中国CIO最关心的八大问题(下)
中国CIO最关心的八大问题(下) 从调研数据还可以看出,在企业级IT建设与投资上,CIO们并非是一群狂热的技术信徒,他们更多的是从企业发展阶段.信息化程度.技术成熟度.ROI等方面进行综合评估. 五. ...
- Visual Studio 2013 添加一般应用程序(.ashx)文件到SharePoint项目
默认,在用vs2013开发SharePoint项目时,vs没有提供一般应用程序(.ashx)的项目模板,本文解决此问题. 以管理员身份启动vs2013,创建一个"SharePoint 201 ...