Ale*_*kha 1 ruby arrays hash insert
我正在做 Ruby 任务,即“你有一个数字数组。你的任务是对升序的奇数进行排序,但偶数必须在它们的位置上。零不是奇数,您不需要移动它。如果您有一个空数组,则需要返回它”。
决定拆分初始数组:将奇数推入另一个数组,对其进行排序并将偶数添加到哈希中,其中键为 num,其初始索引为值。之后,尝试将偶数从哈希插入到奇数数组,在偶数的初始索引处。因此,代码如下所示:
def sort_array(source_array)
even_nums = Hash.new
odd_nums = []
return source_array if source_array.length == 0
source_array.each_with_index {|n, ind| even_nums[n] = ind if n.even?}
source_array.select{|n| odd_nums.push(n) if n.odd?}
odd_nums.sort!
even_nums.each do |k, v|
odd_nums.insert(v, k)
end
odd_nums
end
Run Code Online (Sandbox Code Playgroud)
对于像 [5, 3, 2, 8, 1, 4, 11] 这样的小数组,它可以按预期工作,但是如果我传递更大的东西,例如 [84, -64, 40, 53, 5, 88, 2, 14, 29, -79, -44, -23, 20, -67, -12, 28, -28, -37, -27, -62, -54, 93, -61, 50, 65, -63, -62, 77, -16, 49, -43, 26, -73, -27, 88, -88, -62, 84, 54, 25, 25, -2, -99, 69, -23, 47, -92, 7, -62, -62, -58, -30, -75, -31, 65, -63, 16, 64, -7, -22, -6, -82]
我在排序数组的末尾得到 nils。像这样:
[-99, -64, 40, -79, -75, -73, 2, 14, -67, -63, -44, -63, 20, -61, -12, 28, -28, -43, -37, -31, -54, -27, -27, 50, -23, -23, -7, 5, -16, 7, 25, 26, 25, 29, 47, -88, 49, 53, 54, 65, 65, -2, 69, 77, 93, nil, -92, nil, nil, 88, -58, -30, nil, nil, nil, nil, 16, 64, nil, -22, -6, -82, 84, nil, -62]
Run Code Online (Sandbox Code Playgroud)
努力理解,为什么它不适用于更大的阵列?
如果您将其视为两个操作,则有一种相当简单的方法可以做到这一点:
def sort_array(arr)
# Extract and sort the odd values
odd = arr.select(&:odd?).sort
# Merge the sorted odd values back in
arr.map do |v|
v.odd? ? odd.shift : v
end
end
Run Code Online (Sandbox Code Playgroud)
没什么好说的。
你有一些正确的部分,但我认为当它开始变得过于复杂时,你陷入了困境。
| 归档时间: |
|
| 查看次数: |
48 次 |
| 最近记录: |