两数之和Java

**问题描述:**给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

//采用HashMap存储数组值,进行查找差值的方式,通过Value记录下标。
class Solution {
    
    
    public int[] twoSum(int[] nums, int target) {
    
    
        HashMap<Integer, Integer> hm = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
    
    
            int sub= target - nums[i];
            if (hm.containsKey(sub)) {
    
    
                return new int[] {
    
     map.get(hm), i };
            }
            hm.put(nums[i], i);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43360777/article/details/108358917
今日推荐