給你一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
示例:
給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合爲:
[
[-1, 0, 1],
[-1, -1, 2]
]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/3sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
//轉換成熟悉的題目,兩數之和
//a+b=-c(target)
if (nums == null || nums.length < 3) return Collections.emptyList();
// return threeSumI(nums);
// return threeSumII(nums);
return threeSumIII(nums);
}
//方法三:雙指針法
//先排序,定義3個指針中最小數字的指針i,枚舉i;
//left,right分別位於(i,len(nums))兩端
//s = nums[i] + nums[left] + nums[right]
//如果s > 0,right--;s < 0,left++;s=0,記錄i,left,right
private List<List<Integer>> threeSumIII(int[] nums) {
//先排序,便於去重
Arrays.sort(nums);
List<List<Integer>> result = new LinkedList<>();
//定義i爲三個數中最小數字的指針,枚舉i
for (int i = 0; i < nums.length - 2; i++) {
//如果最小數num[i] > 0,三數之和不可能爲0,跳過
if (nums[i] > 0) break;
//跳過重複值
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
} else {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
//去重
while (left < right && nums[left] == nums[left + 1]) left++;
while (left < right && nums[right] == nums[right - 1]) right--;
left++;
right--;
}
}
}
return result;
}
//方法二:利用Hash表緩存結果,二重循環O(n^2)
private List<List<Integer>> threeSumII(int[] nums) {
Set<List<Integer>> result = new LinkedHashSet<>();
for (int i = 0; i < nums.length - 1; i++) {
Map<Integer, Integer> map = new HashMap<>();
for (int j = i + 1; j < nums.length; j++) {
int target = -nums[i] - nums[j];
if (map.containsKey(target)) {
List<Integer> list = Arrays.asList(nums[i], nums[j], target);
list.sort(Comparator.naturalOrder());
result.add(list);
} else {
map.put(nums[j], nums[j]);
}
}
}
return new ArrayList<>(result);
}
//方法一:暴力求解,三重循環O(n^3)
private List<List<Integer>> threeSumI(int[] nums) {
Set<List<Integer>> result = new LinkedHashSet<>();
//先排序,方便去重
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
for (int k = j + 1; k < nums.length; k++) {
if (nums[i] + nums[j] + nums[k] == 0) {
List<Integer> list = Arrays.asList(nums[i], nums[j], nums[k]);
result.add(list);
}
}
}
}
return new ArrayList<>(result);
}
}