Given in an array n, I want to find all the distinct a, b, c elements such that a+b+c=0. For instance, imagine
n = [-1, 0, 1, 2, -1, -4]
result should be
[ [-1, 0, 1], [-1, -1, 2] ]
I came up with the following algorithm, which I think gives the complexity of O(n^2). My question is, can we make it more efficient computationally?
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> collection = new HashSet<List<Integer>>();
Arrays.sort(nums);
int leadingPointer, tailPointer, container;
for(int i=0; i<nums.length-2; i++){
leadingPointer = i+1;
tailPointer = nums.length-1;
while(leadingPointer<tailPointer){
container = nums[i] + nums[leadingPointer] + nums[tailPointer];
if(container == 0){
collection.add(new ArrayList<Integer> (Arrays.asList(
nums[i],
nums[leadingPointer],
nums[tailPointer]
)));
tailPointer--;
leadingPointer++;
} else if(container > 0){
tailPointer--;
} else{
leadingPointer++;
}
}
}
List<List<Integer>> finalResult = new ArrayList<List<Integer>>();
finalResult.addAll(collection);
return finalResult;
}
}