当前位置:网站首页>leetcode刷题:哈希表04 (两数之和)

leetcode刷题:哈希表04 (两数之和)

2022-06-23 17:23:00 涛涛英语学不进去

力扣题目链接

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9

所以返回 [0, 1]

一上手我就是个暴力破解

    public int[] twoSum(int[] nums, int target) {
    
        int[] result = new int[2];
        //处理初始数组
        for (int i = 0; i < nums.length; i++) {
    
            //因为是两个数,temp为应该出现的结果
            int temp = target - nums[i];
            for (int j = 0; j < nums.length; j++) {
    
                //不能一个数用两次
                if (i == j) {
    
                    continue;
                }
                if (temp == nums[j]) {
    
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return null;
    }

在这里插入图片描述

显然。。不应该这么做。换个思路,用哈希表的思想。

    public static int[] twoSum2(int[] nums, int target) {
    
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        //处理初始数组
        for (int i = 0; i < nums.length; i++) {
    
            int temp = target - nums[i];
            //根据键查找,需要的值是否存在
            if (map.get(nums[i]) != null) {
    
                for (int j = 0; j < nums.length; j++) {
    
                    if (temp == nums[j] && i != j) {
    
                        result[0] = i;
                        result[1] = j;
                        return result;
                    }
                }
            }
            //把下一次需要的值作为键
            map.put(temp, nums[i]);
        }
        return null;
    }

在这里插入图片描述

原网站

版权声明
本文为[涛涛英语学不进去]所创,转载请带上原文链接,感谢
https://blog.csdn.net/niTaoTaoa/article/details/125376675