leetCode 15. 3Sum

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 }
原文地址:https://www.cnblogs.com/yfs123456/p/10888385.html