The problem statement from leetcode says:
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Fin
Your solution may have exceeded the time limit and therefore may have not been able to pass the test cases. Below is the code having the runtime O(n^3)
. Initially, we sort the array which will help us to find the element either by moving forward or backward depending on the number we are looking for. We then take the first element from the array and perform a three sum on the remaining part leading to find the two sum. Only the ArrayList
is used. HashMap
is not required.
public static List> fourSum(int[] nums, int target) {
List> result = new ArrayList>();
if(nums==null|| nums.length<4)
return result;
Arrays.sort(nums);
for(int i=0; itarget)
{
l--;
}
else
{
List t = new ArrayList();
t.add(nums[i]);
t.add(nums[j]);
t.add(nums[k]);
t.add(nums[l]);
result.add(t);
k++;
l--;
while( k