LeetCode 01 --- 两数之和

115 阅读1分钟

题目

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。 LeetCode 1.两数之和

示例1

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0,1]

示例2

输入:nums = [3,2,4], target = 6
输出:[1,2]

示例3

输入:nums = [3,3], target = 6
输出:[0,1]

思路

本题借助map 数据结构只需扫描一遍整数数组即可,时间复杂度为O(N)。从左往右遍历的过程中,对于每一个元素,在map中查找是否存在与该元素相加值为target的数字,若无,则将该元素的数值与对应的数组下标分别作为map的键和值存入map中;若有,则将这两个数字在数组中对应的下标输出。

若数组不在符合条件的解,最后返回数组{-1,-1}。

参考代码

public class LC_01 {
    public int[] twoSum(int[] nums, int target) {
        // 边界检查
        if (nums == null || nums.length < 2) {
            return new int[]{-1, -1};
        }
        int[] res = new int[]{-1, -1};
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]);
                res[1] = i;
                break;
            } else map.put(nums[i], i);
        }
        return res;
    }

}