對不起,如果標題不清楚。我遇到了一個解決的問題,但我希望能夠深入瞭解如何在不使用嵌套循環的情況下解決問題,或者如果有更高效的方法。謝謝!更有效的方法來解決Ruby演習要求返回2個索引,而不使用嵌套循環?
# Write a method that takes an array of numbers. If a pair of numbers
# in the array sums to zero, return the positions of those two numbers.
# If no pair of numbers sums to zero, return `nil`.
def two_sum(nums)
nums.each_with_index do |num, i1|
for i2 in i1 + 1...nums.length
return [i1, i2] if num + nums[i2] == 0
end
end
nil
end
# These are tests to check that your code is working. After writing
# your solution, they should all print true.
puts(
'two_sum([1, 3, 5, -3]) == [1, 3]: ' + (two_sum([1, 3, 5, -3]) == [1, 3]).to_s
)
puts(
'two_sum([1, 3, 5]) == nil: ' + two_sum([1, 3, 5]).nil?.to_s
)
[比較Ruby中的兩個項目](http://stackoverflow.com/questions/33905245/comparing-two-items-in-array-with-ruby) – tebayoso
編號這只是一個比較的元素。這需要返回他們的指數。 –
更高效的,你的意思是比'O(n^2)'更好的時間複雜度,還是隻是看起來更清晰的代碼?兩者都是有效的追求,但最有可能不會看起來一樣。 –