LeetCode:二和问题

leetcode:二和问题

tw%ignore_a_1%sum 问题是一个经典的编码挑战,测试您的问题解决能力和算法技能。

在这篇文章中,我们将首先看看一个易于理解的简单解决方案。然后,我们会逐步优化它,提高它的效率。无论您是算法新手还是准备面试,本指南都将帮助您解决问题。让我们开始吧!

let inputarray = [2, 7, 11, 15]let target = 9console.log(twosum(inputarray, target)) // output: [0, 1]

让我们看看函数应该处理的输入和输出。

给定数组 [2,7,11,15] 和目标 9,输出将为 [0,1].

这是因为索引 0 和 1 处的值加起来为 9,这是目标。

function twosum(nums, target) {  const hashmap = {}}

我们会想到一个解决方案,创建一个 hashmap 将数组中的数字存储为键,将其索引存储为值。

function twosum(nums, target) {  const hashmap = {}  for (let i = 0; i < nums.length; i++) {    hashmap[nums[i]] = i  }}

这是解决方案的第一部分:准备 hashmap。

Perplexity Perplexity

Perplexity是一个ChatGPT和谷歌结合的超级工具,可以让你在浏览互联网时提出问题或获得即时摘要

Perplexity 94 查看详情 Perplexity

在下一个循环中,我们检查 hashmap 是否包含目标减去数组中当前数字的补集。

function twosum(nums, target) {  const hashmap = {}  for (let i = 0; i < nums.length; i++) {    hashmap[nums[i]] = i  }  for (let i = 0; i < nums.length; i++) {    const complement = target - nums[i]    if (hashmap[complement] !== undefined && hashmap[complement] !== i) {      return [i, hashmap[complement]]    }  }}

如果在 hashmap 中找到补集,我们就可以访问它的索引,因为我们有它的值。

然后,我们可以返回一个包含其值(补集的索引)以及 i 的数组,i 表当前迭代。

在此解决方案中,我们看到我们正在创建两个单独的循环。我们可以将它们组合成一个循环,从而节省一次迭代。

function twosum(nums, target) {  const hashmap = {}  for (let i = 0; i < nums.length; i++) {    const complement = target - nums[i]    if (hashmap[complement] !== undefined && hashmap[complement] !== i) {      return [i, hashmap[complement]]    }    hashmap[nums[i]] = i  }}

为了更加清晰,我们改进了条件并获得了以下代码:

function twoSum(nums, target) {  const hashMap = {}  for (let i = 0; i < nums.length; i++) {    const complement = target - nums[i]    if (complement in hashMap) {      return [i, hashMap[complement]]    }    hashMap[nums[i]] = i  }}let inputArray = [2, 7, 11, 15]let target = 9console.log(twoSum(inputArray, target)) // Output: [0, 1]

以上就是LeetCode:二和问题的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/783797.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月26日 10:55:36
下一篇 2025年11月26日 10:55:59

相关推荐

发表回复

登录后才能评论
关注微信