【思路】
蛮力算法,时间复杂度为O(n3),无法ac。我们可以先排序O(nlogn),我们知道2Sum是选定两指针从前后分别向中间扫,找到能找到就直接返回。与2Sum不同的是,3Sum要先选定一个数,再按照2Sum的思路找另两个数,即使找到了,也得继续找下去,不能直接返回。同时,要注意去重:
public List> threeSum(int[] nums) {
ArrayList> result = new ArrayList>();
if (nums.length < 3) return result;
Arrays.sort(nums);
ArrayList temp = null;
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue; //选定nums[i]为第一个数,并去重
int left = i + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == 0) {
temp = new ArrayList();
temp.add(nums[i]);
temp.add(nums[left]);
temp.add(nums[right]);
result.add(temp);
while (left < right && nums[left] == nums[left + 1]) left++; //去重
while (left + 1 < right && nums[right] == nums[right - 1]) right--;
}
if (sum <= 0) left++;
else if (sum >= 0) right--;
}
}
return result;
}
311 / 311
test cases passed. Runtime: 9 ms Your runtime beats 34.07% of javasubmissions.