- 描述
Given an array S of n integers, are there elements a,b,c in S such that a + b + c = 0?
Find all unique triplets in the array which gives the sum of zero.
Note:
• Elementsinatriplet(a,b,c)mustbeinnon-descendingorder.(ie,a≤b≤c)
• Thesolutionsetmustnotcontainduplicatetriplets.
For example, given array S={-1 0 1 2 -1 4}
A solution set is:
(-1 0 1)
(-1 -1 2)
- 分析
有序Two Sum的衍生版,那么可以沿用Two Sum,使Three Sum变成Two Sum,在外层套一个循环即可,时间复杂度为O(n^2)
package leet.ThreeSum;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public static List<Integer> getThreeSum(int[] arr, int target) {
List<Integer> res = new ArrayList<Integer>(6);
if(arr == null || arr.length < 3)
return res;
// 为保证结果集有序,要先排序
Arrays.sort(arr);
for(int i = 0; i < arr.length-2; ++i) {
int low = i + 1;
int high = arr.length - 1;
// 确保结果不会重复
if(i>0 && arr[i] == arr[i-1]) continue;
int sum = target - arr[i];
// Two Sum的解决方法,不同的是要排除重复的,如果重复,则跳过
while(low < high) {
if(arr[low] + arr[high] > sum) {
-- high;
while(arr[high] == arr[high+1] && low < high)
-- high;
}
else if(arr[low] + arr[high] < sum) {
++low;
while (arr[low] == arr[low - 1] && low < high)
++low;
}
else {
res.add(arr[i]);
res.add(arr[low]);
res.add(arr[high]);
++ low;
-- high;
while (arr[low] == arr[low - 1] && arr[high] == arr[high+1] && low < high)
++low;
}
}
}
return res;
}
}