大家好,我是阿飞,今天的题目是演算法初阶题目 Two Sum,让我们一起来看看:
题目来源 Codewars
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).
For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.
The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).
twoSum [1, 2, 3] 4 === (0, 2)
题目要我们把阵列中的数字两两相加,直到相加的结果等於 target,并且回传两个数字在阵列的 index。
看到题目我很快就联想到,以前学 JavaScript 时练习过的印出九九乘法表,便假定要用两个回圈来完成,假设有阵列[0, 1, 2],而目标值是 3,我们第一圈计算 0 + 1 (index 0 和 1)和 0 + 2(index 0 和 2),得到结果分别是 1 和 2,不符合目标值,便进入第二圈,计算 1 + 2(index 1 和 2),便可以得到解答。故,内层的回圈比起外层的回圈,起始值要 + 1。
以下是我的解答:
def two_sum(numbers, target)
i = 0
j = 1
arr = []
while i < numbers.length
while j < numbers.length
if numbers[i] + numbers[j] == target
arr << i
arr << j
break
end
j += 1
end
i += 1
j = i + 1
end
arr
end
对比最佳解答:
def twoSum(numbers, target)
numbers.each_with_index do |n1, i1|
numbers.each_with_index do |n2, i2|
return [i1, i2] if (n1 + n2) == target && i1 != i2
end
end
end
它很高明地用了 each_with_index 拿出阵列里的每个 element 和对应的 index,并在最後加了 i1 != i2 的判断,避免相同 index 数字相加的情况。
好了,今天解题就到这,大家晚安~
熟悉JWT的我敲开了大门的门锁,走进了房间 同学:来,你过来~~ 我:干嘛啦 (被推着坐下),哇,同...
上篇回顾 分布式可观测性 Logging 浅谈 分布式可观测性 Structured Log 分布式...
一日客语:中文:青色 客语:抢厶ㄟ ˋ 继续学习原型吧~ 学习内容: 1.Object.getPro...
前言 今天的文章会再对 Bootstrap 做个 recap, 然後就会稍微对接下来的里程碑 ─ R...
本篇同步发布於个人Blog: [PoEAA] Data Source Architectural P...