java 3sum_3Sum探讨(Java)

探讨一下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]

]

1.暴力解法

时间复杂度高达O(n^3)

public List> threeSum(int[] nums) {

List> lists =new ArrayList>();

for(int i=0;i

for (int j = i + 1; j < nums.length-1; j++) {

for(int z=j+1;z

if(nums[i]+nums[j]+nums[z]==0){

List list =new ArrayList();

list.add(nums[i]);

list.add(nums[j]);

list.add(nums[z]);

lists.add(list);

}

}

}

}

returnlists;

}

运行结果:

239bbc2d42532c9842be6cd2a14192ca.png

结果不尽人意,有个重复的。我想过如果使用list排重的话。必然先要对list进行排序,然后对比是否相等,如果相等,再剔除掉一样的。代码如下:

public static List> three(int[] nums){

List> lists =new ArrayList>();

for(int i=0;i

for (int j = i + 1; j < nums.length-1; j++) {

for(int z=j+1;z

if(nums[i]+nums[j]+nums[z]==0){

List list =new ArrayList();

boolean flag = true;

list.add(nums[i]);

list.add(nums[j]);

list.add(nums[z]);

Collections.sort(list);

for(int k=0;i

if(list.equals(lists.get(i))){

flag = false;}

}

if(flag){

lists.add(list);

}

}

}

}

}

returnlists;

}

运行结果:

1232a91233af296d57ee500635c629b3.png

看着貌似问题解决了,但是Runtime=2ms,时间有点长,时间复杂度太高了。

上交的时候爆出来一个错误:

5bbd83e2fed607919652cce3fbaa2bbc.png

既然结果都能运行出来,为什么还爆数组越界呢?我也看不出来什么毛病。

2.使用map

时间复杂度为O(n+n^2),即O(n^2)

public List> threeSum(int[] nums) {

List> lists =new ArrayList>();

Map map =new HashMap();

for(int i=0;i

map.put(num[i],i);

}

for(int i=0;i

for(int j=i+1;j

int res=0-nums[i]-nums[j];

if(map.containsKey(res)&&map.get(res)!=i&&map.get(res)!=j){

List list =new ArrayList();

list.add(res);

list.add(nums[i]);

list.add(nums[j]);

lists.add(list);

}

}

}

returnlists;

}

这个的运行结果让人头疼。

1442e8b704e4e47ab706fa89a3be7a1e.png

有没有好的办法可以排重,如果这样的话,时间复杂度是O(n^2):

public List> threeSum(int[] nums) {

Arrays.sort(nums);

List> lists =new ArrayList>();

Map map =new HashMap();

for(int i=0;i

for(int j=i+1;j

int res=0-nums[i]-nums[j];

if(map.containsKey(res)){

List list =new ArrayList();

list.add(res);

list.add(nums[i]);

list.add(nums[j]);

lists.add(list);

}

}

map.put(nums[i],i);

}

returnlists;

}

运行结果:

8d0274054e3d136108169b9da6559074.png

这下结果正确了,提交一下:

f9508e5eb9d81afe7bcfc8ff5d4c6af5.png

对于上面的数组,算法是不成立的。我把上面的list排重写进里面,但是就是解决不了问题。请高手帮我解决问题,共同学习。

附上leetcode这个问题的地址:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值