xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

LeetCode 两数之和 算法题解 js 版 All In One

LeetCode 两数之和 算法题解 js 版 All In One

001 Two Sum

https://leetcode.com/problems/two-sum/submissions/

https://leetcode-cn.com/problems/two-sum/submissions/

// 1. 双重循环 ✅
function twoSum(nums: number[], target: number): number[] {
  let temp;
  for (let i = 0; i < nums.length; i++){
    temp = nums[i]
    for (let j = i + 1; j < nums.length; j++){
      if (temp + nums[j] === target){
        return [i, j].sort()
      }
    }
  }
}

// 2. 对象字典 ✅ 
// function twoSum(nums: number[], target: number): number[] {
//   const dict = {}
//   for (const [i, item] of Object.entries(nums)) {
//     const temp = target - item;
//     if(dict[temp]) {
//       return [i, dict[temp]].sort()
//     } else {
//       dict[item] = i;
//     }
//   }
// };

// 3. Map 字典 ✅ 
// function twoSum(nums: number[], target: number): number[] {
//   const dict = new Map()
//   for (const [i, item] of Object.entries(nums)) {
//     const temp = target - item;
//     if(dict.has(temp)) {
//       return [i, dict.get(temp)].sort()
//     } else {
//       dict.set(item, i)
//     }
//   }
// };

// 3. hack 一次替换 ✅ 
// function twoSum(nums: number[], target: number): number[] {
//   for (const [i, item] of Object.entries(nums)) {
//     const temp = target - item;
//     const arr = [...nums]
//     // X 替换
//     arr[i] = `X`;
//     const index = arr.indexOf(temp)
//     if(index !== -1)  {
//       return [parseInt(i), index].sort()
//     }
//   }
// };

/* 

Testcase Source

[2,7,11,15]
9
[3,2,4]
6
[3,3]
6
[2,5,5,11]
10
[-1,-2,-3,-4,-5]
-8

 */

1. 暴力解法

Time complexity: O(n**2)
Space complexity: O(n)


"use strict";

/**
 * @author xgqfrms
 * @description leetcode problems: two-sum & https://leetcode.com/problems/two-sum/
 * @language JavaScript & ES6
 * 
 * @param {Int Number Array} nums
 * @param {Int Number} target
 * @return {Int Number Array} result
 * 
 */

let twoSum = (nums = [2, 7, 11, 15], target = 9) => {
    let result = [];
    for(let i =  0; i < nums.length; i++){
        for(let ii =  0; ii < nums.length; ii++){
            let temp_a = nums[i];
            let temp_b = nums[ii];
            if(ii !== i){
                let temp_result = temp_a + temp_b;
                if(temp_result === target){
                    // 1. reset;
                    // result = [];
                    // result.push(i);                    
                    // result.push(ii);
                    // 2. remove duplication
                    if(!result.includes(i)){
                       result.push(i);
                    }
                    if(!result.includes(ii)){
                       result.push(ii);
                    }
                    result.sort();
                }
            }else{
                // break;
            }
        }
    }
    return result;
};

2. 一遍 Hash Table

Time complexity: O(n)
Space complexity: O(n)


// Time complexity: O(n)
// Space complexity: O(n)

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
  let result = [];
  // 空间换时间  HashMap / Object
  const obj = {};
  for(let i = 0; i < nums.length; i++) {
    let temp = target - nums[i];
    if(obj[nums[i]] !== undefined) {
      result = [obj[nums[i]], i];
      break;
    } else {
      obj[temp] = i;
    }
  }
 return result;
};


ES6

Map & WeakMap


bugs

// bug

/*

var twoSum = function(nums, target) {
    let result = [];
    for(let i = 0; i < target; i++) {
      let temp = target - i;
      if(nums.includes(temp) && nums.includes(i)) {
        result = [nums.indexOf(i), nums.indexOf(temp)];
        break;
      }
    }
   return result;
};

*/

best solutions

https://leetcode-cn.com/submissions/detail/112453419/

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    var map=new Map();
    for(let i=0;i<nums.length;i++){
        if(!map.has(target-nums[i])){
            map.set(nums[i],i);
        }else{
            return [map.get(target-nums[i]),i]
        }
    }
};
/**
 * 注:此题使用ES6的Map,使得时间复杂度降为O(n)
 * 关于Map和Set的使用要重点掌握!!!
 * 我觉得思路很棒,继续理解!
 */

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function(nums, target) {
    let i = nums.length;
    while(i > 1) {
        let last = nums.pop();
        if (nums.indexOf(target - last) > -1){
            return [nums.indexOf(target - last),nums.length];
        }
        i--
    }
}

demos

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2020-09-29 23:12  xgqfrms  阅读(192)  评论(1编辑  收藏  举报