Leetcode 三数之和、四数之和
三数之和

class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i - 1]) continue;
int oppositeNum = -nums[i];
int j = i + 1, k = nums.length - 1;
while(j < k){
if(nums[j] + nums[k] > oppositeNum){
k--;
}else if(nums[j] + nums[k] < oppositeNum){
j++;
}else{
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
res.add(temp);
while(j < k && nums[j] == nums[j + 1]) j++;
while(j < k && nums[k] == nums[k - 1]) k--;
j++;
k--;
}
}
}
return res;
}
}
四数之和

class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
for(int j = nums.length - 1; j >= 0; j--){
while(j != nums.length - 1 && j != 0 && nums[j] == nums[j + 1]) j--;
while(i != nums.length - 1 && i != 0 && nums[i] == nums[i - 1]) i++;
int low = i + 1, high = j - 1;
while(low < high){
if(nums[i] + nums[j] + nums[low] + nums[high] < target){
low++;
}else if(nums[i] + nums[j] + nums[low] + nums[high] > target){
high--;
}else{
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[low]);
temp.add(nums[high]);
temp.add(nums[j]);
res.add(temp);
low++;
high--;
while(low < high && nums[high] == nums[high + 1]) high--;
while(low < high && nums[low] == nums[low - 1]) low++;
}
}
}
}
return res;
}
}