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

refs



©xgqfrms 2012-2021

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

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


posted @   xgqfrms  阅读(194)  评论(1编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-09-29 js & Object not equal
2018-09-29 css & no margin & print pdf
2018-09-29 fetch api & response header
2018-09-29 ACE in Action
2018-09-29 用Windows自带DOS命令提示符 制作U盘启动盘
2016-09-29 How to make you Look Like a Professional Hacker All In One
2015-09-29 微软2016校园招聘9月在线笔试
点击右上角即可分享
微信分享提示