四数之和
📃 题目描述
🔔 解题思路
仿照上面 15. 三数之和 - 力扣(LeetCode) (leetcode-cn.com) (opens new window)的题解,我们枚举前三个数,然后 Hash 最后一个数:
package com.kami.leetcode.hash_table;
import java.util.*;
/**
* @Description: TODO
* @author: scott
* @date: 2022年02月11日 10:10
*/
public class Solution_18 {
public List<List<Integer>> fourSum(int[] nums, int target){
//存储四元组
List<List<Integer>> res = new ArrayList<>();
if(nums == null || nums.length < 4){
return res;
}
//对数组进行排序
Arrays.sort(nums);
// key: 数组元素, value: 该元素对应的下标
Map<Integer, Integer> map = new HashMap<>();
// 将数组存入 map, 相等的值只会放进去一个,
for(int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
// 三层循环决定 a b c
// 遍历获得 a
for(int i = 0; i < nums.length; i++){
// 对 a 进行去重
if(i > 0 && nums[i] == nums[i - 1]){
continue;
}
// 遍历获得 b
for(int j = i + 1; j < nums.length; j++){
// 对 b 进行去重
if(j > i + 1 && nums[j] == nums[j - 1]){
continue;
}
// 遍历获得 c
for(int k = j + 1; k < nums.length; k++){
// 对 c 进行去重
if(k > j + 1 && nums[k] == nums[k -1]){
continue;
}
// map 中查找最后一个数 d
int temp = target - nums[i] - nums[j] - nums[k];
if(map.containsKey(temp) && map.get(temp) > k){
res.add(Arrays.asList(nums[i], nums[j], nums[k], temp));
}
}
}
}
return res;
}
}