The difference between the collection list array

Insert picture description here
Given an integer array nums and an integer 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.

You can return the answers in any order
Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, return [0, 1].

Use Hash algorithm

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

Guess you like

Origin blog.csdn.net/weixin_42789301/article/details/113360295