您的位置:首页 > 编程语言 > Java开发

leetCode练习(15)

2016-09-15 15:16 399 查看
题目:3Sum

难度:medium

问题描述:

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.

解题思路:

先对数组进行排序可以极大的减少枚举次数。同时,我是先做了18题~是15题的提高版,因此直接用了18题的方法偷工取巧。具体代码如下:

public class Solution {
public List> threeSum(int[] nums) {
ArrayList> res=new ArrayList>();
int len=nums.length;
if(nums==null||len<3){
return res;
}
Arrays.sort(nums);
int max=nums[len-1];
if(nums[0]>0||max<0){
return res;
}
int i,z;
for(i=0;i0&&z==nums[i-1])		continue;
if((z+2*max)<0)			continue;
if(z>0)					break;
if(z==0){
if((i+2)> foursumlist,int z1){
if(low>=high)		return;
if(2*nums[low]>target||2*nums[high]target){
j--;
}
}
return;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode int