三数之和的延申,四数之和:两层外层for循环+双指针
时间复杂度:O(n3)
空间复杂度:O(1)
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FourSum {
@Test
public void test() {
int[] nums = new int[]{1, 0, -1, 0, -2, 2};
for (int i = 0; i < fourSum(nums,0).size(); i++) {
System.out.println(fourSum(nums,0).get(i));
//[2,-1,1,2],[-2,0,0,2],[-1,0,0,1]
}
int[] nums1 = new int[]{2, 2, 2, 2};
for (int i = 0; i < fourSum(nums1,8).size(); i++) {
System.out.println(fourSum(nums1,8).get(i));
}
}
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 - 4; i++) {//避免越界
if (i > 0 && nums[i] == nums[i - 1]) {//nums = [2,2,2,2]的情况时,在i == 0,j == i+1的时候完成存入
continue;
}
for (int j = i + 1; j <= nums.length - 3; j++) {
if (j > i+1 && nums[j] == nums[j - 1]) {
continue;
}
int l = j + 1, r = nums.length - 1;
while (l < r) {
int sum = nums[i] + nums[j] + nums[l] + nums[r];
if (sum == target) {
res.add(Arrays.asList(nums[i],nums[j], nums[l], nums[r]));
//处理相同的数的情况
//因为最后输出的nums数组中的值,不是索引,所以数字相同可以直接跳过
while (l < r && nums[l] == nums[++l]) ;
while (l < r && nums[r] == nums[--r]) ;
} else if (sum < target) {
l++;
} else {
r--;
}
}
}
}
return res;
}
}
详情见三数之和
lc15.三数之和_鬼鬼写bug的博客-CSDN博客