我對以下問題的解決方案感到驚訝。如何針對ruby中的Two_sum代碼優化解決方案
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
這是在參考C++代碼http://leetcodeunlock.com/2016/05/20/leetcode-1-two-sum-easy/後提交的紅寶石解決方案。
def two_sum(nums, target)
hash = {}
arr = []
nums.each_with_index do |value,index|
y = target - value
if(hash.find{|key,val| key == value})
arr << hash[value]
arr << index
return arr
else
hash[y] = index
end
end
end
我的提交失敗,消息:超出時間限制。任何人都可以指出錯誤並幫助我優化代碼?
我認爲一個很大的問題是,您可能遍歷'nums'數組中幾乎每個值的大散列。嘗試從保持索引的方式開始,然後對數組進行排序並從兩端開始工作。 – hlee
看看這個[so question](http://stackoverflow.com/questions/25213818/checking-to-see-if-2-numbers-in-array-sum-to-0-in-ruby)for想法。 –