【Sum of two numbers】

question:

Given an integer array nums and an integer target value target, please find the two integers in the array whose sum is the target value target and return their array subscripts.

You can assume that each input will correspond to only one answer. However, the same element in the array cannot appear repeatedly in the answer.

You can return answers in any order.

Example 1:

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

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Excellent answer: Hash table

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

hashtable.containsKey(key): Whether to contain a specific key

Guess you like

Origin blog.csdn.net/m0_46459413/article/details/129246495