gpt4 book ai didi

ruby - 合并两个排序数组 - 为什么这不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:00:00 26 4
gpt4 key购买 nike

我正在学习 ruby​​,并被分配了以下作业:

given two sorted arrays like the following we must merge them into one sorted array.
array_1 = [5,8,9,11]
array_2 = [4,6,7,10]

merge(array_1, array_2)

=> [4,5,6,7,8,9,10,11]

Given this brief description, implement the merge method that takes two arrays and returns
the properly sorted array containing the items from each array.

我写了这个答案:

def merge(arr1, arr2)
i = 0
k = 0
merged_arr = []
until k = arr2.count
while arr1[i] <= arr2[k]
merged_arr.push(arr1[i])
i += 1
end
merged_arr.push(arr2[k])
k += 1
end
merged_arr
end

我的导师发出了一个解决方案,我理解,但我不明白为什么我的答案不起作用。有人可以解释错误的逻辑吗?谢谢!

这是(正确的)解决方案:

def merge(array_1, array_2)
i = 0
k = 0
merged_array = []
while i < array_1.count
while k < array_2.count && array_1[i] > array_2[k]
merged_array << array_2[k]
k += 1
end
merged_array << array_1[i]
i += 1
end
print merged_array.inspect
end

最佳答案

k = arr2.countarr2.count 的值赋给 k 并计算为 k,所以 until k = arr2.count 永远不会执行。

关于ruby - 合并两个排序数组 - 为什么这不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24233649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com