[LeetCode]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]
]
解题思路
- 将3Sum问题转换为2Sum问题,
a1+a2+a3=0 <-> a1 + a2 = -a3(target)
,故可考虑遍历一遍数组,将其中每个数都设为target一次,则该层循环内部就只需要解决2Sum问题; - 2Sum问题可以考虑先将数组排序,然后使用双指针,如果
nums[left]+nums[right] < nums[taget]
,则右移左指针,<则左移有指针,=就找到了一组期望的结果; - 还有一点需要想清楚的是,大循环内层解决2Sum问题时,left指针永远只需要从target的下一位开始,因为前面的实际上已经被处理过了。
代码
public class Sum3 {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int target=0; target<nums.length-1; target++) {
int left = target+1, right = nums.length-1;
if(target !=0 && nums[target] == nums[target-1]) continue;//重复的target不需要再计算
while(left < right) {
int sum = nums[left] + nums[right] + nums[target];
if(sum > 0) right--;
else if(sum < 0) left++;
else {
List<Integer> oneResult = new ArrayList<Integer>();
oneResult.add(nums[target]);
oneResult.add(nums[left]);
oneResult.add(nums[right]);
//避免出现重复的三元组
if(resultList.size() > 0) {
ArrayList<Integer> temp = (ArrayList<Integer>) resultList.get(resultList.size()-1);
if(temp.get(0) == nums[target] && temp.get(1) == nums[left] && temp.get(2) == nums[right]) {}
else resultList.add(oneResult);
} else resultList.add(oneResult);
if(nums[left+1] != nums[left]) right--;
else left++;
}
}
}
return resultList;
}
public static void main(String[] args) {
int[] nums = {-1, 0, 1, 2, -1, -4};
List<List<Integer>> resultList = threeSum(nums);
for(int i=0; i<resultList.size(); i++) {
for(int j=0; j<3; j++)
System.out.print(resultList.get(i).get(j) + " ");
System.out.println();
}
}
}
感想
嘛~还是个用双指针解题的题~感觉主要恶心的地方在于避免重复~博主年轻不懂事还试了用Set存储,之后再倒腾到List里面,结果太耗时被LeetCode斩杀=。=