15. 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组
示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
public class LeetCode15 {
class Compare implements Comparator<List<Integer>> {
@Override
public int compare(List<Integer> o1, List<Integer> o2) {
int n = o1.size();
int m = o2.size();
n = Math.min(n, m);
for (int i = 0; i < n; ++i) {
if (o1.get(i) > o2.get(i)) {
return 1;
} else if (o1.get(i) < o2.get(i)) {
return -1;
} else {
continue;
}
}
return 0;
}
}
public static void main(String[] args) {
// Scanner scanner = new Scanner(System.in);
// String input = scanner.next();
// String[] n = input.split(",");
// int[] ins = new int[n.length];
// for (int i = 0; i < n.length; ++i) {
// ins[i] = Integer.parseInt(n[i]);
// }
int[] nums ={-1,0,1,2,-1,-4,3,5,7,-2,-3,-4,6,8};
List<List<Integer>> res = new LeetCode15().threeSum(nums);
for (List<Integer> list : res) {
System.out.print("[");
boolean first = true;
for (int e : list) {
if (first) {
first = false;
} else {
System.out.print(",");
}
System.out.print(e);
}
System.out.print("]");
}
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int len = nums.length;
if (nums == null || len < 3) return res;
Arrays.sort(nums);
for (int i = 0; i < len; ++i) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = len - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
List<Integer> tmp = Arrays.asList(nums[i], nums[left], nums[right]);
res.add(tmp);
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
} else if (sum < 0) left++;
else {
right--;
}
}
}
return res;
}
}