The sum of two numbers Java

**Problem description:** Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array, and return their array subscripts.
You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice.

//采用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);
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_43360777/article/details/108358917