3sum java_[Java教程]15. 3Sum

[Java教程]15. 3Sum

0

2016-05-13 17:00:05

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)

代码如下:(超时)1 public class Solution { 2 public List> threeSum(int[] nums) { 3 List> list1=new ArrayList<>(); 4 List list=new ArrayList<>(); 5 Map,List> map=new HashMap<>(); 6 int a=0; 7 8 Arrays.sort(nums); 9 10 for(int i=0;i<=nums.length-3;i++)11 {12 if(nums[i]<=0)13 {14 list.add(nums[i]);15 a=nums[i]*(-1);16 }17 else break;18 for(int j=i+1;j<=nums.length-2;j++)19 {20 if(nums[j]<=a)21 {22 list.add(nums[j]);23 a=a-nums[j];24 for(int k=j+1;k<=nums.length-1;k++)25 {26 if(nums[k]>a)27 break; 28 else if(nums[k]==a)29 {30 list.add(nums[k]);31 if(!map.containsKey(list))32 {33 map.put(list, list);34 list1.add(list);35 }36 break;37 }38 39 }40 }41 else break;42 list=new ArrayList<>();43 list.add(nums[i]);44 a=nums[i]*(-1);45 }46 list=new ArrayList<>();47 }48 49 return list1;50 }51 }

本文网址:http://www.shaoqun.com/a/221193.html

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。

0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值