给一个数组和一个目标值k,从数组中找出3个值,要求这三个数相加后等于目标值k。返回所有符合这个条件的三个值,同时这三个值的字面量要去重,不能一样。
将3元组问题化解成2元组问题。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class C_3Sum {
public static List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums); // 先排序
List<List<Integer>> ans = new ArrayList<>();
for (int i = nums.length-1; i > 1; i--) {
if(i == nums.length-1 || nums[i] != nums[i+1]) {
int target = 0 - nums[i];
List<List<Integer>> lists = twoSum(nums, i - 1, target);
for (List<Integer> cur : lists) {
cur.add(nums[i]);
ans.add(cur);
}
}
}
return ans;
}
// nums[0...end]这个范围上,有多少个不同二元组,相加==target,全返回
// {-2,9} K = 7
// {1, 6}
public static List<List<Integer>> twoSum(int[] nums, int end, int target) {
List<List<Integer>> ans = new ArrayList<>();
int L = 0;
int R = end;
while (L < R){
if(nums[L] + nums[R] > target){
R--;
}else if(nums[L] + nums[R] < target){
L++;
}else{
if(L == 0 || nums[L-1] != nums[L]){
List<Integer> cur = new ArrayList<>();
cur.add(nums[L]);
cur.add(nums[R]);
ans.add(cur);
}
L++;
}
}
return ans;
}
public static void main(String[] args) {
//System.out.println("main...");
int[] nums = {-1,0,1,2,-1,-4};
List<List<Integer>> lists = threeSum(nums);
for(List<Integer> cur : lists){
for(Integer i : cur){
System.out.print(i+" ");
}
System.out.println();
}
}
}
471

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



