- 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:

Main Trouble: Time Limit

Solution
Time Complexity: O(n^2), Space Complexity: O(n)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> triplets = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i = 0; i < nums.length-2; i++) {
// to solve time limit exceed problem
if(nums[i] > 0)
break;
if(i > 0 && nums[i-1] == nums[i])
continue;
int start = i+1;
int end = nums.length-1;
while(start < end) {
if(nums[i] + nums[start]+nums[end] == 0) {
List<Integer> triplet = new ArrayList<Integer>();
triplet.add(nums[i]);
triplet.add(nums[start]);
triplet.add(nums[end]);
triplets.add(triplet);
start++;
end--;
// to remove the duplicate
while(start < end && nums[start-1] == nums[start]) {
start++;
}
while(start < end && nums[end+1] == nums[end]) {
end--;
}
} else if(nums[i] + nums[start]+nums[end] > 0)
end--;
else
start++;
}
}
return triplets;
}
}
本文详细探讨了3Sum问题的解决方法,即在一个整数数组中寻找三个元素a、b、c,使得它们的和等于0。通过使用排序和双指针技术,实现了O(n^2)的时间复杂度和O(n)的空间复杂度,有效避免了重复解的问题。

856

被折叠的 条评论
为什么被折叠?



