正如標題所述,我正在尋找兩個總和等於目標整數的元素。我已經制定了下面的解決方案,但這隻適用於唯一整數。涉及到重複值時,我遇到了問題。當然,我可以使用多個循環來記錄兩個單獨的索引,並以這種方式確保這兩個索引相同。但是,我想知道是否有一種方法可以通過一次迭代來解決這個問題。給定一個整數和目標數組,如果任意兩個元素總和爲目標,則返回true
two_sum([1,2,3,4,5,6], 8) = true
two_sum([4,4], 8) = false
def two_sum(array, target)
idx = 0
while idx < array.length
complement = target - array[idx]
if array.include?(complement) && complement != array[idx]
return true
end
idx+=1
end
return false
end
'array.combination(2).any? {| a,b | a + b == target}' – steenslag
我建議'array.combination(2).find {| a,b | a + b == target}',它返回所需的對或'nil'。編輯:Egad! @steenslag在我做之前幾分鐘內發佈了幾乎完全相同的評論,甚至是相同的塊變量!我確實認爲'find'比'any''更受歡迎,因爲所需的一對是想要的。 –
@CarySwoveland從頭部:「...如果任何兩個元素總和爲目標,則返回true」。 – steenslag