g0001_0100.s0015_3sum.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java11 Show documentation
Show all versions of leetcode-in-java11 Show documentation
Java Solution for LeetCode algorithm problems, continually updating
The newest version!
package g0001_0100.s0015_3sum;
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Sorting #Two_Pointers
// #Data_Structure_II_Day_1_Array #Algorithm_II_Day_3_Two_Pointers #Udemy_Two_Pointers
// #2022_06_14_Time_28_ms_(71.04%)_Space_59.7_MB_(30.50%)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@SuppressWarnings("java:S127")
public class Solution {
public List> threeSum(int[] nums) {
Arrays.sort(nums);
final int len = nums.length;
List> result = new ArrayList<>();
int l;
int r;
for (int i = 0; i < len - 2; i++) {
l = i + 1;
r = len - 1;
while (r > l) {
int sum = nums[i] + nums[l] + nums[r];
if (sum < 0) {
l++;
} else if (sum > 0) {
r--;
} else {
List list = new ArrayList<>();
list.add(nums[i]);
list.add(nums[l]);
list.add(nums[r]);
result.add(list);
while (l < r && nums[l + 1] == nums[l]) {
l++;
}
while (r > l && nums[r - 1] == nums[r]) {
r--;
}
l++;
r--;
}
}
while (i < len - 1 && nums[i + 1] == nums[i]) {
i++;
}
}
return result;
}
}