Leetcode sum of two numbers uses JavaScript to solve problems

Some people are in love, some people drive at night to see the sea, I can’t solve the first problem of leetcode

topic

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

You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer.

Input: nums = [2,7,11,15], target = 9

output: [0,1]

Explanation: Because nums[0] + nums[1] == 9, return [0, 1].

Method 1: Brute force cracking

When I first saw this problem, the solution I thought of was to use a for loop, two for loops to traverse, add each item, and when it is equal to the target, you can return their subscripts

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

This method belongs to brute force cracking, enumerating every possibility, although it can solve the problem, it consumes a lot of performance, time complexity: O(N^2), where N is the number of elements in the array. In the worst case, any two numbers in the array must be matched once.

Method 2: Hash

A hash table can be created. For each one x, we first query whether it exists in the hash table target - x, and then xinsert into the hash table to ensure that it will not xmatch itself.

Specific steps are as follows:

  • Step 1: Create a map
  • Step 2: for loop through the array
  • Step 3: Subtract each item from target, and calculate which number can be added to the current number to get target
  • Step 4: Check if there is such a number in the map, and if so, return the result, if not, put nums[i] as key and i as value into the map
var twoSum = function(nums, target) {
    
    
    let map = new Map();
    for(let i=0;i<nums.length;i++){
    
    
        let resault =  target - nums[i]
        if(map.has(resault)){
    
    
            return [map.get(resault),i]
        }else{
    
    
            map.set(nums[i],i)
        }
    }
    return []
};

knowledge points

MapObjects hold key-value pairs and are able to remember the original insertion order of the keys. Any data type can be used as a key or value

  • Mapsome basic operations of
// 创建一个map对象
const map = new Map()
// 添加键值
map.set('a',1)
// 删除值
map.delete('a')
// 是否存在某一个键
map.has('a')
// 获取map的长度(不用带括号)
map.size

Guess you like

Origin blog.csdn.net/buruyang/article/details/126202479