数据结构与算法【LeetCode-Offer】:3.9哈希表—四数之和

四数之和

📃 题目描述

题目链接
在这里插入图片描述

🔔 解题思路

仿照上面 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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狂野小白兔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值