LeetCode/com/zerroi/leetcode/Three13/ThreeSum.java

53 lines
1.7 KiB
Java
Raw Normal View History

2024-03-14 20:58:23 +08:00
package com.zerroi.leetcode.Three13;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ThreeSum {
public static void main(String[] args) {
SolutionFirst solutionFirst = new SolutionFirst();
List<List<Integer>> res = solutionFirst.threeSum(new int[]{-1,0,1,2,-1,-4});
res.forEach(System.out::println);
}
}
/*
* 给你一个整数数组 nums 判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i != ji != k j != k 同时还满足 nums[i] + nums[j] + nums[k] == 0
你返回所有和为 0 且不重复的三元组
注意答案中不可以包含重复的三元组
* */
class SolutionFirst {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 1; i++) {
if (i > 0 &&nums[i] == nums[i - 1]) {
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (left < right ) {
int sum = nums[left] + nums[right] + nums[i];
if (sum == 0) {
res.add(List.of(nums[left], nums[right], nums[i]));
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
left++;
} else if (sum > 0) {
right--;
} else {
left++;
}
}
}
return res;
}
}