这道题是Two Sum的扩展,暴力法时间复杂度为O(n^3),对每三个数进行比较,显然是不可取的。这道题和Two Sum有所不同,使用哈希表的解法并不是很方便,因为结果数组中元素可能重复,如果不排序对于重复的处理将会比较麻烦,因此这道题一般使用排序之后夹逼的方法,总的时间复杂度为O(n^2+nlogn)=(n^2),空间复杂度是O(n),代码如下:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
// -4,-1,-1,0,1,2
int len = nums.length;
for(int i = 0; i < len - 2; i++){
if (i != 0 && nums[i] == nums[i - 1]) {
continue; // to skip duplicate numbers; e.g [0,0,0,0]
}
int k = len - 1;
int j = i + 1;
while(j < len - 1 && j < k){
List<Integer> temp = new ArrayList<Integer>();
if(nums[i] + nums[j] + nums[k] < 0){
j++;
}else if(nums[i] + nums[j] + nums[k] > 0) {
k--;
}else{
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
result.add(temp);
j++;
k--;
while (j < k && nums[j] == nums[j - 1]) { // to skip duplicates
j++;
}
while (j < k && nums[k] == nums[k + 1]) { // to skip duplicates
k--;
}
}
}
}
return result;
}
public static void main(String[] args) {
int[] nums = {-1, 0, 1, 2, -1, -4};
System.out.println(threeSum(nums));
}
}