LC-the sum of two numbers

1. Problem

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.

Example:

Given nums = [2, 7, 11, 15], target = 9

Because nums[0] + nums[1] = 2 + 7 = 9,
it returns [0, 1]

Author: stay button (LeetCode)
link: https: //leetcode-cn.com/leetbook/read/tencent/xxqfy5/
Source: stay button (LeetCode)
copyright reserved by the authors. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

2. Code processing

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

3. Analysis

Both space complexity and time complexity are O(n)

Guess you like

Origin blog.csdn.net/qq_28500837/article/details/110134500