# Blankj/awesome-java-leetcode

Fetching contributors…
Cannot retrieve contributors at this time
71 lines (52 sloc) 2.09 KB

# 3Sum

## Description

Given an array `nums` of n integers, are there elements a, b, c 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]
]
``````

Tags: Array, Two Pointers

## 思路

```class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
int len = nums.length;
if (len < 3) return list;
Arrays.sort(nums);
int max = nums[len - 1];
if (max < 0) return list;
for (int i = 0; i < len - 2; ) {
if (nums[i] > 0) break;
if (nums[i] + 2 * max < 0) {
while (nums[i] == nums[++i] && i < len - 2) ;
continue;
}
int left = i + 1, right = len - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
while (nums[left] == nums[++left] && left < right) ;
while (nums[right] == nums[--right] && left < right) ;
} else if (sum < 0) ++left;
else --right;
}
while (nums[i] == nums[++i] && i < len - 2) ;
}
return list;
}
}```

## 结语

You can’t perform that action at this time.