leetcode 18. 4Sum 题目,但是其解题思路可以延伸到 ksum
package com.protobuf.ACM;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by liuchaoqun01 on 2019/2/19.
*/
public class Ksum {
/**
* 对于此类问题,一般的解决思路是先排序. 然后将前k-2个数字进行循环,在剩下的范围内设置两个指针p,q.
* 遍历p,q的值, 直到达到target
*/
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; ++i) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 2; ++j) {
// 这里j一定是大于i + 1
if (j > i + 1 && nums[j] == nums[j - 1]) {continue;}
int left = j + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
// 命中以后再来判断重复
if (sum == target) {
List<Integer> tmp = Arrays.asList(nums[i], nums[j], nums[left], nums[right]);
res.add(tmp);
// 避免重复值
while (left < right && nums[left] == nums[left + 1]) {
++left;
}
while (left < right && nums[right] == nums[right - 1]) {
--right;
}
++left;
--right;
} else if (sum < target) {
++ left;
} else {
-- right;
}
}
}
}
return res;
}
public static void main(String[] args) {
int[] nums = {0,0,0,0};
int target = 0;
List<List<Integer>> res = Ksum.fourSum(nums, target);
System.out.println("ok");
}
}
参考:
1 ksum
网友评论