有人可以向我解釋這個 hashMap 演算法背后的邏輯嗎?我對演算法如何接收總和感到困惑。我開始學習演算法,所以對我來說有點困惑。我在代碼中添加了注釋以查明每一行代碼,但我不確定我是否正確掌握了邏輯。我只是在尋找一種更簡單的方法來理解演算法的作業原理,以避免混淆自己。
//**calculate Two Number Sum
func twoNumberSum(_ array: [Int], _ targetSum: Int) -> [Int] {
//1) initilize our Array to hold Integer Value: Boolean value to store value into hashTable
var numbersHashMap = [Int:Bool]()
//2) create placeHolder called number that iterates through our Array.
for number in array {
//3) variable = y - x
let match = targetSum - number
//4) ??
if let exists = numbersHashMap[match], exists {
//5) match = y / number = x
return [match, number] //
} else {
//6) Store number in HashTable and repeats
numbersHashMap[number] = true
}
}
return []
}
twoNumberSum([3,5,-4, 8, 11, 1, -1, -6], 10)
// x = Number
// y = Unknown *Solve for Y*
uj5u.com熱心網友回復:
當然,我可以帶你過去。所以我們有一個數字串列,我們是否正在嘗試找到兩個相加以形成指定目標的數字。為此,對于每個數字 x,我們檢查 (target - x) 是否在串列中。如果不是,那么我們將 x 添加到串列中。如果是,那么我們回傳 x 和 (target - x)。
您代碼中的第 4 步是我們檢查 (target - x) 是否在串列中的部分。為了了解為什么這是有道理的,讓我們來看一個例子。
假設我們有 [2, 3, -1] 并且我們的目標是 1。在這種情況下,我們首先考慮 x = 2 并檢查我們的哈希圖是否 (target - x) = (1 - 2) = -1。由于 -1 不在哈希圖中,我們將 2 添加到哈希圖中。然后我們考慮 x = 3 并檢查 (1 - 3) = -2。同樣,-2 不在哈希圖中,所以我們添加它。現在我們檢查 x - -1。在這種情況下,當我們檢查 (target - x) = (1 - (-1)) = 2 時,2 在哈希圖中。直觀上,我們已經“看到”了 2,并且知道可以將 2 和 -1 相加得到我們的值。
這就是在檢查串列中每兩個數字時提供速度優化的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/396585.html
