Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

1.两数之和 #1

Open
Open
Labels
@Geekhyt

Description

@Geekhyt

原题链接

1.暴力法

符合第一直觉的暴力法,潜意识里要学会将两数之和转换为两数之差

然后问题就变得像切菜一样简单了,双层循环找出当前数组中符合条件的两个元素,并将它们的索引下标组合成数组返回即所求。

consttwoSum=function(nums,target){for(leti=0;i<nums.length;i++){for(letj=i+1;j<nums.length;j++){if(nums[i]===target-nums[j]){return[i,j]}}}}
  • 时间复杂度:O(n^2)
  • 空间复杂度:O(1)

写出这种方法是不会让面试官满意的,所以接下来我们要想办法进行优化。

2.借用 Map

算法优化的核心方针基本上都是用空间换时间。

我们可以借用 Map 存储遍历过的元素及其索引,每遍历一个元素时,去 Map 中查看是否存在满足要求的元素。

如果存在的话将其对应的索引从 Map 中取出和当前索引值组合为数组返回即为所求,如果不存在则将当前值作为键,当前索引作为值存入。

题目要求返回的是数组下标,所以 Map 中的键名是数组元素,键值是索引。

consttwoSum=function(nums,target){constmap=newMap()for(leti=0;i<nums.length;i++){constdiff=target-nums[i]if(map.has(diff)){return[map.get(diff),i]}map.set(nums[i],i)}}
  • 时间复杂度:O(n)
  • 空间复杂度:O(n)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp