Leetcode1-100: 15. 3Sum
问题描述
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]
]
题目要求是输入一个数组,给出所有和为0的三元组的集合。
解题思路
- Brute force 生成所有三元组,然后判断是否需要加入结果集中(可以先排序然后实现来确保不加入重复的三元组)
- 排序扩展法, 先排序,确定一个元素之后,找后续的元素中有没有两个元素的和是选中元素的负数。由于先排序了,可以用头尾指针线性的过一遍就可以找到对应的元素。需要注意的是由于不能加入重复的三元组,所以添加了一组后可以移动头尾指针来确保没有重复的元素加进去。
代码实现
implement 1 Brute force
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
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) {
if(!(res.contains(Arrays.asList(nums[i], nums[j], nums[k])))){
res.add(Arrays.asList(nums[i], nums[j], nums[k]));
}
}
}
}
}
return res;
}
果然,时间复杂度太高了,遇到很长的串就超时了。
implement 2 扩展中心法
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new LinkedList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++) {
int start = i+1, end = nums.length - 1, target = -nums[i];
while(start < end) {
if(nums[start]+nums[end] > target)
end--;
else if(nums[start]+nums[end] < target)
start++;
else {
res.add(Arrays.asList(nums[i], nums[start], nums[end]));
//去掉重复的元素,防止start指向重复的元素
while(start < nums.length - 1 && nums[start] == nums[start+1]) start++;
//去掉重复的元素,防止end指向重复的元素
while(end > 0 && nums[end] == nums[end-1]) end--;
start++;
end--;
}
}
//去掉重复的元素,防止i指向重复的元素
while(i < nums.length - 1 && nums[i] == nums[i+1]) i++;
}
return res;
}
复杂度分析
对于实现1的brute force方法,时间复杂度是O(n4)(因为ArrayList.contains()函数也需要线性的时间复杂度), 空间复杂度是O(C3n)
对于实现2的方法, 时间复杂度是O(n2), 空间复杂度是O(C3n)
分析
这题的排序是比较重要的一点,因为排完序之后线性查找可以节省很多时间。
另外,leetcode似乎对于O(n2)以上的算法几乎不可能通过,因为经常会有很长的输入。
PS:感觉这样写出所有算法的行为不大有效,今天明明直接用的第二种实现。后来写博客的时候又现写了个brute force,来给出一个“time exceeds limit”的结果,讲真不是很必要,后面如果实现方法很简单没什么亮点就不加了吧, 简单提一下就可以。