LeetCode-1. 两数之和 -Java

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum

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

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

你可以按任意顺序返回答案。

示例 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 中找定值的另⼀半数字,如果找到了,直接返回 2 个数字的下标即可。
如果找不到,就把这个数字保存到 map 中,等待找到另一个数字的时候,再取出来返回结果。key保存值,value保存下标(反过来,没影响)

class Solution {
    
    
    public int[] twoSum(int[] nums, int target) {
    
    
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length ; i++) {
    
    
            if (map.containsKey(target - nums[i])){
    
    
                return new int[]{
    
    map.get(target - nums[i]),i};
            }
            map.put(nums[i] , i);
        }
        return null;       
    }
}

时间复杂度是 O(n)

猜你喜欢

转载自blog.csdn.net/weixin_44695700/article/details/113830533
今日推荐