3Sum
given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]Basic Idea:
Java Code:
Last updated
given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]Last updated
// 从左到右,以每个数为第一个数,用双指针确定另外两数
// 为了避免重复,相同的元素只选第一个做第一个数,如果有重复,需要跳过
// 时间复杂度为 O(n^2)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length < 3) return res;
Arrays.sort(nums);
for (int i = 0; i < nums.length; ++i) {
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) {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[left++]);
temp.add(nums[right--]);
res.add(temp);
// 关键两行:
while (left > 0 && left < right && nums[left] == nums[left - 1]) left++;
while (right < nums.length - 1 && left < right && nums[right] == nums[right + 1]) right--;
}
else if (sum > 0) right--;
else left++;
}
}
return res;
}
}class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; ++i) {
map.put(nums[i], i); // 最后一个数的index,方便后面去重
}
List<List<Integer>> ret = new ArrayList<>();
for (int i = 0; i < nums.length - 2; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j < nums.length - 1; ++j) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
if (nums[i] + 2 * nums[j] == 0 && nums[j + 1] == nums[j]) {
ret.add(new ArrayList<>(Arrays.asList(nums[i], nums[j], nums[j])));
} else if (map.containsKey(0 - nums[i] - nums[j])
&& map.get(0 - nums[i] - nums[j]) > j // 只考虑j后面出现的k,去重) {
ret.add(
new ArrayList<>(Arrays.asList(nums[i], nums[j], 0 - nums[i] - nums[j])));
}
}
}
return ret;
}
}