题目

给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

样例

如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:

(-1, 0, 1)

(-1, -1, 2)

注意

在三元组(a, b, c),要求a <= b <= c。

结果不能包含重复的三元组。

解题:

法一:直接暴力,时间复杂度是O(N3)

public class Solution {
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
// write your code here ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(numbers == null || numbers.length<3)
return result;
for(int i = 0;i< numbers.length - 2 ; i++){
ArrayList<Integer> path = new ArrayList<Integer>();
for(int j = i+1;j < numbers.length - 1 ; j++){
for(int k = j+ 1 ; k < numbers.length ; k++)
if(numbers[i] + numbers[j] + numbers[k] == 0 ){
path = sort3(numbers[i],numbers[j],numbers[k]);
if(result.contains(path)==false)
result.add(path);
}
}
}
return result;
}
public ArrayList<Integer> sort3(int a,int b,int c){
ArrayList<Integer> path = new ArrayList<Integer>();
if(a>b){
int tmp = a;
a = b;
b = tmp;
}
if(c<=a){
path.add(c);
path.add(a);
path.add(b);
}else if(c>=b){
path.add(a);
path.add(b);
path.add(c);
}else{
path.add(a);
path.add(c);
path.add(b);
}
return path; } }

Java Code

在运行到94%的测试数据的时候WA,下面答案只是第三个和第二个的顺序不一样,怎么能就算错了?

法二:

将原数组存放中ArrayList中,通过判断 -(nums[i]+nums[j]) 是否在ArrayList中,少了第三个for循环,时间复杂度O(N2)增加了空间发杂度O(N)

public class Solution {
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
// write your code here
ArrayList<Integer> path = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(numbers == null || numbers.length<3)
return result;
ArrayList<Integer> nums = new ArrayList<Integer>();
for(int i = 0 ;i < numbers.length ; i++)
nums.add(numbers[i]);
for(int i = 0;i< nums.size() - 2;i++){
for(int j = i+ 1; j<nums.size() -1;j++){
int sum = -((Integer)nums.get(i) + (Integer)nums.get(j));
if(nums.contains(sum) && nums.indexOf(sum) !=j && nums.indexOf(sum) !=i){
path = sort3(sum,nums.get(i),nums.get(j));
if(result.contains(path)==false)
result.add(path);
}
}
}
return result;
}
public ArrayList<Integer> sort3(int a,int b,int c){
ArrayList<Integer> path = new ArrayList<Integer>();
if(a>b){
int tmp = a;
a = b;
b = tmp;
}
if(c<=a){
path.add(c);
path.add(a);
path.add(b);
}else if(c>=b){
path.add(a);
path.add(b);
path.add(c);
}else{
path.add(a);
path.add(c);
path.add(b);
}
return path; } }

Java Code

但是运行还是出现上面的情况

法三:

三个数的和基础还是两个数的和两个数的和||,a+b+c = 0,等价于a+b = -c,这样就和两个数的和|| 很类似,当然也可以参考两个数的和I求解。

先对数组排序,排序后的数组,定义其实节点i,然后对i+1 到len内的所有节点进行两端遍历,这里利用二分查找的思想,

设两端的两个下标是left 和right ,显然 sum=nums[i] + nums[left] + nums[right] >0时候 ,right--,小于0的时候left++,等于0的时候就是答案。时间复杂度O(NlogN)

public class Solution {
/**
* @param numbers : Give an array numbers of n integer
* @return : Find all unique triplets in the array which gives the sum of zero.
*/
public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
// write your code here ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(numbers == null || numbers.length<3)
return result;
Arrays.sort(numbers);
for(int i = 0;i<numbers.length; i++){
int left = i+ 1;
int right = numbers.length - 1;
while(left < right){
int sum = numbers[i] + numbers[left] + numbers[right];
ArrayList<Integer> path = new ArrayList<Integer>();
if(sum==0){
path.add(numbers[i]);
path.add(numbers[left]);
path.add(numbers[right]);
if(result.contains(path)==false)
result.add(path);
left++;
right--;
}else if(sum>0){
right--;
}else{
left++;
}
}
} return result;
} }

Java Code

总耗时: 1094 ms

class Solution:
"""
@param numbersbers : Give an array numbersbers of n integer
@return : Find all unique triplets in the array which gives the sum of zero.
"""
def threeSum(self, numbers):
# write your code here
result = []
if numbers == None or len(numbers) < 3:
return result
numbers.sort()
numlen = len(numbers)
for i in range(numlen):
left = i + 1
right = numlen - 1
while left < right:
sum = numbers[i] + numbers[left] + numbers[right]
if sum==0:
path = [numbers[i],numbers[left],numbers[right]]
if path not in result:
result.append(path)
left +=1
right -=1
elif sum>0:
right -=1
else:
left +=1 return result

Python Code

总耗时: 195 ms

lintcode:三数之和的更多相关文章

  1. lintcode: 三数之和II

    题目 三数之和 II 给一个包含n个整数的数组S, 找到和与给定整数target最接近的三元组,返回这三个数的和. 样例 例如S = .  和最接近1的三元组是 -1 + 2 + 1 = 2. 注意 ...

  2. [LeetCode] 3Sum Smaller 三数之和较小值

    Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 < ...

  3. [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 ...

  4. [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 ...

  5. LeetCode 16. 3Sum Closest. (最接近的三数之和)

    Given an array S of n integers, find three integers in S such that the sum is closest to a given num ...

  6. LeeCode数组第15题三数之和

    题目:三数之和 内容: 给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中 ...

  7. LeetCode第十六题-找出数组中三数之和最接近目标值的答案

    3Sum Closest 问题简介: 给定n个整数的数组nums和整数目标,在nums中找到三个整数,使得总和最接近目标,返回三个整数的总和,可以假设每个输入都只有一个解决方案 举例: 给定数组:nu ...

  8. 南大算法设计与分析课程OJ答案代码(4)--变位词、三数之和

    问题 A: 变位词 时间限制: 2 Sec  内存限制: 10 MB提交: 322  解决: 59提交 状态 算法问答 题目描述 请大家在做oj题之前,仔细阅读关于抄袭的说明http://www.bi ...

  9. python三数之和

    给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组. 注意:答案中不可以包含重复的三元组. ...

随机推荐

  1. 联想预装win8系统改成win7操作步骤及注意事项

    联想消费台式机与一体机预装Windows8改装Windows7的操作步骤及常见问题 前提说明: 目前联想出厂预装Windows 8的台式和一体机使用都是UEFI+GPT硬盘的组合,并且开启了安全启动, ...

  2. Informix 物联网应用示例(转)

    相关概念 MQTT 是一个物联网传输协议,它被设计用于轻量级的发布/订阅式消息传输,旨在为低带宽和不稳定的网络环境中的物联网设备提供可靠的网络服务.MQTT 是专门针对物联网开发的轻量级传输协议.MQ ...

  3. PHP中$_REQUEST中包含的数据,数据被覆盖问题

    这个问题涉及到php.ini中的两个变量. variables_order = "EGPCS" variables_order 系统在定义PHP预定义变量,EGPCS 是 Envi ...

  4. 关于SQLite的创建以及使用相关说明

    关于SQLite的创建以及使用相关说明 没有给出具体的程序,但看完这后可能对你有所帮助. 数据库操作基本知识: execSQL(String sql): 执行一个数据库语句 insert(table, ...

  5. zendframework 事件管理(一)

    zend里的事件管理器主要是为了实现: 1.观察者模式 2.面向切面设计 3.事件驱动构架 事件管理最基本的功能是将监听器与事件连接或断开.不论时连接还是断开都是通过shared collection ...

  6. js中typeof可以准确判断哪些变量类型

    typeof 运算符返回一个用来表示表达式的数据类型的字符串.  可能的字符串有:"number"."string"."boolean".& ...

  7. SSHDroid(SSH Server for Android)通过PC或命令连接android

    1.下载berserker.android.apps.sshdroid.apk .(如果你懒的下载,给我留言,我会发给你) 2.安装到手机,显示如图: 简单解释一下:一般android系统没有root ...

  8. VBS基础篇 - 运算符

    VBScript 有一套完整的运算符,包括算术运算符.比较运算符.连接运算符和逻辑运算符. 运算符优先级: 首先计算算术运算符,然后计算比较运算符,最后计算逻辑运算符. 所有比较运算符的优先级相同,即 ...

  9. 谈谈php中上传文件的处理

    这是一个表单的时代... 我们在浏览器中编辑自己的信息,会遇到上传头像:在文库中,我们会上传文档......到处存在“上传”这个词. php是最好的语言(其他语言的程序猿们不要打我...).php在处 ...

  10. [sql server、oracle] 分组取最大值最小值常用sql

    sqlserver2005前: --分组取最大最小常用sql--测试环境if OBJECT_ID('tb') is not null drop table tb;gocreate table tb(  ...