星空网 > 软件开发 > Java

15. 3Sum

Given an array S of n integers, are there elements abc 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<List<Integer>> threeSum(int[] nums) { 3     List<List<Integer>> list1=new ArrayList<>(); 4     List<Integer> list=new ArrayList<>(); 5     Map<List<Integer>,List<Integer>> 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 }

 




原标题:15. 3Sum

关键词:

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

货物跨境运输:https://www.goluckyvip.com/tag/93232.html
跨境货物运输:https://www.goluckyvip.com/tag/93233.html
跨境货运运输:https://www.goluckyvip.com/tag/93234.html
跨境电商货运险:https://www.goluckyvip.com/tag/93235.html
跨境自发货:https://www.goluckyvip.com/tag/93236.html
跨境货运进口:https://www.goluckyvip.com/tag/93237.html
蓝色港湾地址及周边景点介绍(让你轻松玩转这个美丽的海滨城市):https://www.vstour.cn/a/362185.html
宁夏室内景点大全 宁夏旅游景点有哪些:https://www.vstour.cn/a/362186.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流