In the Leetcode 3Sum problem solution in Java programming Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Leetcode 3Sum problem solution in Java programming
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if(nums==null||nums.length<3)
return res;
int n=nums.length;
Arrays.sort(nums);
for(int i=0;i<n-2;i++) {
if(i>0 && nums[i]==nums[i-1])
continue;
int j=i+1;
int k=n-1;
while(j<k) {
if(nums[i]+nums[j]+nums[k]==0) {
List<Integer> lis = new ArrayList<>();
lis.add(nums[i]);
lis.add(nums[j]);
lis.add(nums[k]);
res.add(lis);
j++;
k--;
while(j<k && nums[j]==nums[j-1])
j++;
while(j<k && nums[k]==nums[k+1])
k--;
}else if(nums[i]+nums[j]+nums[k]<0) {
j++;
}else {
k--;
}
}
}
return res;
}
}
Also read,
- Leetcode 3Sum problem solution in C++
- Leetcode 3Sum problem solution in C
- Leetcode 3Sum problem solution in Python
- Leetcode 3Sum problem solution in C#