BiruLyu
7/15/2017 - 1:52 AM

## 15. 3Sum(#).java

``````public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
int len =  nums.length;
int minNum;

for (int i = 0; i < len - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1])
continue;
int a, b, c;

a = nums[i];
if (a > 0)
return result;

int low = i + 1, high = len - 1;
minNum = -a - nums[high];
while(low < len && nums[low] < minNum) ++low;

while (low < high) {
b = nums[low];
c = nums[high];
if (a + b + c > 0) {
high--;
} else if (a + b + c < 0) {
low++;
} else {
while (low < high && nums[low] == nums[low + 1]) {
low++;
}
while (low < high && nums[high] == nums[high - 1]) {
high--;
}
low++;
high--;

}
}

}
return result;
}
}``````
``````public class Solution {
public List<List<Integer>> threeSum(int[] nums) {

if(nums.length < 3) return res;

Arrays.sort(nums);

for (int i = 0; i < nums.length-2; i++){
if (i > 0 && nums[i] == nums[i-1]){
continue;
}
int element1 = nums[i];
int j = i + 1;
int k = nums.length - 1;
while(j < k){
if (j > i + 1 && nums[j] == nums[j-1]){
j++;
continue;
}
int tempSum = element1 + nums[j] + nums[k];
if (tempSum == 0) {