In the Leetcode 4Sum problem solution in Java programming Given an array nums of n integers, return an array of all the unique quadruplets [nums[a], nums[b], nums[c], nums[d]] such that:
0 <= a, b, c, d < n
a, b, c, and d are distinct.
nums[a] + nums[b] + nums[c] + nums[d] == target
You may return the answer in any order.
Leetcode 4Sum problem solution in Java programming
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
if(nums.length < 4) return new ArrayList();
List<List<Integer>> res = new ArrayList();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 3; i++){
for(int j = nums.length - 1; j > i + 2; j--){
int start = i + 1, end = j - 1;
while(start < end){
int sum = nums[i] + nums[j] + nums[start] + nums[end];
if(sum == target){
List<Integer> arr = new ArrayList(Arrays.asList(nums[i], nums[start], nums[end], nums[j]));
if(!res.contains(arr))
res.add(arr);
end --;
start ++;
}else if(sum > target){
end --;
}else start ++;
}
}
}
return res;
}
}
Also read,
- Leetcode 4Sum problem solution in C++
- Leetcode 4Sum problem solution in C
- Leetcode 4Sum problem solution in Python
- Leetcode 4Sum problem solution in C#