当前位置:网站首页>Leetcode (question 1) - sum of two numbers

Leetcode (question 1) - sum of two numbers

2022-06-24 04:56:00 Xiaobai, a vegetable seller

One 、 subject
Given an array of integers nums And an integer target value target, Please find... In the array And is the target value target the Two Integers , And return their array subscripts . You can assume that each input corresponds to only one answer . however , The same element in the array cannot be repeated in the answer . You can return the answers in any order .
Two 、 Example

// Example 1 
 Input :nums = [2,7,11,15], target = 9
 Output :[0,1]
 explain : because  nums[0] + nums[1] == 9 , return  [0, 1] 

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

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

3、 ... and 、 Their thinking
The idea of solving this problem is to do double traversal , Pass during traversal if Judge whether the sum of two numbers is equal to target equal . If equal, it returns directly , If they are not equal, they will traverse again .

/** * @param {number[]} nums * @param {number} target * @return {number[]} */
var twoSum = function(nums, target) {
    
    let length = nums.length
    for(let i = 0; i < length; i++) {
    
        for(let j = i + 1; j < length; j++) {
    
            if(nums[i] + nums[j] === target) {
    
                return [i, j]
            }
        }
    }
};

 Insert picture description here
At this point, we can see that the time complexity is relatively high , by O(n ^ 2), The space complexity is O(1).
Four 、 expand
We can increase the time complexity to O(n ^ 2) within , At this point, we can use the hash table to solve , You can traverse every element nums[i], And then determine target - nums[i] Exists in the hash table , If there is , Then the array is returned directly , If it doesn't exist , Then put the element and its subscript into the hash table .

/** * @param {number[]} nums * @param {number} target * @return {number[]} */
var twoSum = function(nums, target) {
    
    let map = new Map()
    let length = nums.length
    for(let i = 0; i < length; i++) {
    
        if(map.has(target - nums[i])) {
    
            return [map.get(target - nums[i]), i]
        }
        map.set(nums[i], i)
    }
};

 Insert picture description here
At this point, we can see that the time complexity is O(n), The space complexity is O(n), The space complexity may be high , However, it does not violate the idea of exchanging space for time .

原网站

版权声明
本文为[Xiaobai, a vegetable seller]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211636010903.html