【题目1】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]
]
【解析】
根据题目的意思,需要在一个数组中找到所有的三元组,使这3个数的和为0.跟Two Sum这道题很像。只不过这道题是找出所有可行的结果,并且结果集中不能存在重复。
这道题依然有两种思路,最直接的想法是进行3重循环,遍历所有的可能,这样的时间效率是O(n^3).显然,时间效率过高。
思路2:先对数组进行排序(递增),效率是O(nlogn),然后先确定第一个值,再在有序的序列中查找两个满足要求的数。由于是有序的,所以查找效率是O(n),因此,总体的时间效率是O(n^2).
public static List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
Set<List<Integer>> res = new HashSet<List<Integer>>();
for(int i=0;i<nums.length;i++){
int target = 0 - nums[i];
int j = i+1, k=nums.length-1;
while(j<k){
if(nums[k] + nums[j] == target){
List<Integer> tmp = new ArrayList<Integer>();
tmp.add(nums[i]);
tmp.add(nums[j]);
tmp.add(nums[k]);
res.add(tmp);
j++;
k--;
}
else if(nums[k] + nums[j] < target)
j++;
else
k--;
}
}
return new ArrayList<List<Integer>>(res);
}
【题目2】3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
【解析】
这道题跟上面的类似,解题思路是一样的。先对数组进行排序,然后确定第一个数,再在有序的数组中遍历找到最接近目标值的数。
public static int threeSumClosest(int[] nums, int target) {
if(nums == null || nums.length < 3)
return 0;
Arrays.sort(nums);
int res = 0;
int diff = Integer.MAX_VALUE;
int len = nums.length;
for(int i=0;i<len-2;i++){
int j = i+1, k=len-1;
while(j<k){
int sum = nums[i] + nums[j] + nums[k];
if(Math.abs(sum - target) < diff){
diff = Math.abs(sum - target);
res = sum;
}
if(sum < target){
j++;
}else if(sum > target){
k--;
}else{
return sum;
}
}
}
return res;
}