15. 3Sum
Given an array S of n integers, are there elements a, b, c in S 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.
For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
解法一
采用双指针解法,先将数组进行从小到大排序,将nums[i]作为固定值,j=i+1,及k=length-1,当三者相加和>0时,j–;当三者相加和小于零时,i++; 当相邻的两个i对应数值相等时,后面的i可跳过,省去计算;当三个数值相加和为0时,如果nums[j]和nums[j++],对应数值相等,则j++,取最大的j,同理,如果相邻的k相等,取最小的k。
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if(nums.length == 0 && nums == null) {
return null;
}
List<List<Integer>> result = new LinkedList<>();
Arrays.sort(nums);
int i = 0;
while (i < nums.length - 1) {
int j = i + 1;
int k = nums.length - 1;
if(i == 0 || i > 0 && nums[i] != nums[i - 1]) {
while (j < k) {
List<Integer> temp = new ArrayList<>();
while (nums[i] + nums[j] + nums[k] < 0 && j < k) {
j++;
}
while (nums[i] + nums[j] + nums[k] > 0 && j < k) {
k--;
}
if (nums[i] + nums[j] + nums[k] == 0 && j < k) {
while (j < k && nums[j] == nums[j + 1]) j++;
while (j < k && nums[k] == nums[k - 1]) k--;
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
j++;
k--;
}
}
i++;
} else {
i++;
}
}
return result;
}
}
解法二
解法一的优化版本
注意数组的越界问题,每次都要加条件限制,否则每次循环会越界。
public class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if (nums.length == 0 && nums == null) {
return null;
}
List<List<Integer>> result = new LinkedList<>();
Arrays.sort(nums);
int i = 0;
while (i < nums.length - 2) {
while (i > 0 && nums[i] == nums[i - 1] && i < nums.length - 2) {
i++;
}
int j = i + 1;
int k = nums.length - 1;
while (j < k) {
List<Integer> temp = new ArrayList<>();
while (nums[i] + nums[j] + nums[k] < 0 && j < k) {
j++;
}
while (nums[i] + nums[j] + nums[k] > 0 && j < k) {
k--;
}
if (nums[i] + nums[j] + nums[k] == 0 && j < k) {
while (j < k && nums[j] == nums[j + 1]) j++;
while (j < k && nums[k] == nums[k - 1]) k--;
result.add(Arrays.asList(nums[i], nums[j], nums[k]));
j++;
k--;
}
}
i++;
}
return result;
}
}