算法的实战(二):LeetCode -- twoSum

一 题目描述

给定一个整数数组和一个目标值,找

出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

二 解题思路

1. 构建一个hashMap,将target目标值减掉给定数组的元素值得到的数值作为数组的key,被减数的索引作为该新hashMap的值

2.遍历给定数组的,当target目标值减掉-数组元素的值存在数组的key,则拿出该数组的索引以及list的key所对应的值即可得到的索引

3.这样最坏的情况是遍历数组一次,即时间复杂度只有O(n),对于直接暴力法(O(n^2))优化很多

三 代码实战

public static int[] twoSum(int[] numbers, int target) {

        int[] a = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (int i = 0; i < numbers.length; i++){

            if (map.containsKey(numbers[i])){

                a[0] = map.get(numbers[i]);
                a[1] = i + 1;
                return a;
            }
            map.put(target - numbers[i], i);
        }

        return a;
    }

四 总结点

当需要重复用到或者比较某个value时,我可以用某种方式先存起来,这样就不用重复遍历或者比较

猜你喜欢

转载自blog.csdn.net/m0_38082440/article/details/82875581
今日推荐