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

两数之和

📃 题目描述

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

🔔 解题思路

最简单的思路就是穷举,嵌套遍历,不过显然时间复杂度太高:

package com.kami.leetcode.hash_table;

/**
 * @Description: TODO
 * @author: scott
 * @date: 2022年01月26日 9:04
 */
public class Solution_1 {
    public int[] twoSum(int[] nums, int target){
    
       for(int i = 0; i < nums.length; i++){
            for(int j = i + 1; j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    return new int[] {i, j};
                }
            }
        }
        //不存在这两个数的时候
        return new int[0];
    }
}

可以通过一个哈希表减少时间复杂度:哈希表的 key 对应元素的值,哈希表的 value 对应元素的下标(因为题目需要返回的就是下标),比如某个元素值为 2,就将这个元素的下标存放在哈希表的 key = 2 的 value 上。这样,我们只需要遍历一遍数组,查看 map 中 target - nums[i] 对应的键值对是否存在(并且还要注意这个数不能是 nums[i] 本身),就能知道有没有元素能和 2 组成 target 了。

package com.kami.leetcode.hash_table;

import java.util.HashMap;

/**
 * @Description: TODO
 * @author: scott
 * @date: 2022年01月26日 9:04
 */
public class Solution_1 {
    public int[] twoSum(int[] nums, int target){

        if(nums == null || nums.length == 0){
            return new int[0];
        }

        //创建一个HashMap,key: 元素值, value: 元素下标
        HashMap<Integer, Integer> hashM = new HashMap<>();

        // 处理数组存入 hashM
        for(int i = 0; i < nums.length; i++){
            hashM.put(nums[i], i);
        }

        //遍历数组来判断
        for(int i = 0; i < nums.length; i++){

            // 当前元素 nums[i] + j = target
            int j = target - nums[i];
            // 在 map 中查找下 j 对应的键值对是否存在, 并且还要注意这个数不能是 nums[i] 本身
            if(hashM.containsKey(j) && hashM.get(j) != i){
                return new int[] {i, hashM.get(j)};
            }
        }

        return new int[0];

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

狂野小白兔

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

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

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

打赏作者

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

抵扣说明:

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

余额充值