2016-11-23 39 views
0

正如標題所述,我正在尋找兩個總和等於目標整數的元素。我已經制定了下面的解決方案,但這隻適用於唯一整數。涉及到重複值時,我遇到了問題。當然,我可以使用多個循環來記錄兩個單獨的索引,並以這種方式確保這兩個索引相同。但是,我想知道是否有一種方法可以通過一次迭代來解決這個問題。給定一個整數和目標數組,如果任意兩個元素總和爲目標,則返回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 

回答

0
def two_sum(array, target) 
    array.combination(2).each { |pair| return true if pair.inject(:+) == target } 
    return false; 
end 
+5

'array.combination(2).any? {| a,b | a + b == target}' – steenslag

+2

我建議'array.combination(2).find {| a,b | a + b == target}',它返回所需的對或'nil'。編輯:Egad! @steenslag在我做之前幾分鐘內發佈了幾乎完全相同的評論,甚至是相同的塊變量!我確實認爲'find'比'any''更受歡迎,因爲所需的一對是想要的。 –

+1

@CarySwoveland從頭部:「...如果任何兩個元素總和爲目標,則返回true」。 – steenslag

2
require 'set' 

def two_sum(arr, tot) 
    st = Set.new 
    arr.each { |n| st.include?(tot-n) ? (return true) : st << n } 
    false 
end 

two_sum [1,2,3,4,5,6], 8 #=> true 
two_sum [4,4], 8   #=> true 
two_sum [1,2,3,4,5,6], 3421 #=> false 

如果您願意返回兩個值是總和tot(當true),與[n, tot-n]替換true(或只返回n,另一個是tot - n)。

我使用了一個集合而不是一個數組來進行更快的查找。

+0

它是O(n)對O(n ** 2)。太好了! – pjs

相關問題