求三数之和为0
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:不能包含重复的三元组
原题链接:https://leetcode-cn.com/problems/3sum/
题解
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
if (nums.length >= 3) {
int length = nums.length;
List<Integer> temp;
for (int i = 0; i < length; i++) {
if (nums[i] == nums[i - 1]) continue;
int left = i + 1;
int right = length - 1;
while (left < right) {
if (nums[left] + nums[right] > -nums[i])
right--;
else if (nums[left] + nums[right] < -nums[i])
left++;
else {
temp = new LinkedList<>();
temp.add(nums[i]);
temp.add(nums[left]);
temp.add(nums[right]);
result.add(temp);
if (left < right && nums[left] == nums[left + 1]) continue;
if (left < right && nums[right] == nums[right - 1]) continue;
right--;
left++;
}
}
}
}
return result;
}