18. 四数之和
和第17题,一样的策略,证明思路也是类似的。
操作的话,就是先确定好最小两个数字,然后按照【有序数组里面两数之和】的方式来求解,去重也是类似,不能在同一个位置,取两次相同的数字。
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> ans = new ArrayList<>();
if (nums == null || nums.length < 4) {
return ans;
}
Arrays.sort(nums);
for (int i = 0; i <= nums.length - 4; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
for (int j = i + 1; j <= nums.length - 3; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int temptar = target - nums[i] - nums[j];
int left = j + 1, right = nums.length - 1;
while (left < right) {
int temp = nums[left] + nums[right];
if (temp < temptar) left++;
else if (temp > temptar) right--;
else {
List<Integer> tempans = new ArrayList<>();
tempans.add(nums[i]);
tempans.add(nums[j]);
tempans.add(nums[left]);
tempans.add(nums[right]);
ans.add(tempans);
left++;
while (left < nums.length && nums[left] == nums[left - 1]) left++;
}
}
}
}
return ans;
}