Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
sort the input array and then run through all indices of a possible first element of a triplet.
for each possible first element, use two pointers like in 2sum problem
skip equal elements to avoid duplicates in the answer without a set
注意:在skip same element的时候,l和r的方法是相反的,应该判断nums[l] = nums[l-1]和nums[r] = nums[r+1]
时间:O(N^2),空间:O(1)
class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> res = new ArrayList<>(); for(int i = 0; i + 2 < nums.length; i++) { if(i == 0 || (i > 0 && nums[i] != nums[i - 1])) { int l = i + 1, r = nums.length - 1, target = -nums[i]; while(l < r) { if(nums[l] + nums[r] == target) { res.add(Arrays.asList(nums[i], nums[l], nums[r])); l++;r--; while(l < r && nums[l] == nums[l - 1]) l++; while(l < r && nums[r] == nums[r + 1]) r--; } else if(nums[l] + nums[r] > target) { r--; } else { l++; } } } } return res; } }
原文地址:https://www.cnblogs.com/fatttcat/p/10039480.html
时间: 2024-10-11 05:49:33