码迷,mamicode.com
首页 > 其他好文 > 详细

leetCode 15. 3Sum

时间:2019-05-19 11:47:44      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:bre   nbsp   lis   new   rip   3sum   code   not   tin   

Given an array nums of n integers, are there elements abc in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

有空没空也得记得刷道题啊,不然乍一敲代码手生的很啊。

 1 class Solution {
 2     public List<List<Integer>> threeSum(int[] nums) {
 3         List<List<Integer>> list = new ArrayList<>();//存放List<Integer>数组元素
 4         Arrays.sort(nums);
 5         int length = nums.length;
 6         for (int i = 0; i < length-2; i++) {
 7             if (i != 0 && nums[i] == nums[i-1])
 8                 continue;
 9             for (int j = i+1; j < length-1; j++) {
10                 if (nums[i] + nums[j] + nums[length-1] < 0)
11                     continue;
12                 int th = nums[i] + nums[j];
13                 if(th > 0)//确保nums[i]+nums[j] < 0
14                     continue;
15 
16                 for (int i1 = nums.length - 1; i1 > j; i1--) {
17                     if (nums[i1] + th == 0) {
18                         if (list.size() > 0) {
19                             List<Integer> l = list.get(list.size()-1);
20                             if (l.get(0) == nums[i] && l.get(1) == nums[j] && l.get(2) == nums[i1]) {
21                                 break;
22                             }
23                         }
24                         ArrayList<Integer> listElem = new ArrayList<>();
25                         listElem.add(nums[i]);
26                         listElem.add(nums[j]);
27                         listElem.add(nums[i1]);
28                         list.add(listElem);
29                         break;
30                     }
31                     else if (nums[i1] + th < 0)
32                         break;
33                 }
34             }
35         }
36 
37         return list;
38     }
39 }

 

leetCode 15. 3Sum

标签:bre   nbsp   lis   new   rip   3sum   code   not   tin   

原文地址:https://www.cnblogs.com/yfs123456/p/10888385.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!