First of all, thank you, @Nyx for some HUGE clues.
A few things . . .
-
I believe the "value < target" test should be "value <= target" because it is possible to have COMPLEMENT = 0 for example an "8 + 0 = 8" solution.
-
The return value has to be an array and can't be a tuple per problem specifications. The fixed header was provided as follows:
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
-
I moved things around so they would match the "build complement" first before the "test" portion of the program.
-
I thought that I could lookup a Dictionary table row by VALUE, when in fact it can only be done by KEY.
As shown in this page:
And this page:
I was unable to find any way to do something like var someVar = someDict[value] instead of var someVar = someDict[key] using the square bracket syntax.
If anyone knows how to do this, or if this is possible to lookup a dictionary row by value using the square brackets, please advise.
So, to make the whole thing work, the hash table build had to be dictionary[value] = index instead of dictionary[index] = value which feels logically backwards to me, but it works in this case because both sets, index and value, have unique values with no duplicates, so it doesn't matter to the computer.
(Apologies for all the debug print statements, I was stuck on this issue for quite a while.)
let complement = target - value
lookup[complement] = index
Was the proper way to build the hash table. I believe the hash table was supposed to be built as an identical copy of the input array nums.
Thank you, again, for all your fine clues and wisdom.
Here is Version 2 :
// Version 2
class Solution {
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dictionary: [Int: Int] = [:]
for (index, value) in nums.enumerated(){
// print("for index: \(index) value: \(value)")
guard value <= target else {
continue
}
var complement = target - value
// print("var target: \(target) - value: \(value) = complement: \(complement)")
// print("PREIFLET dictionary: \(dictionary)")
// print("PREIFLET dictionary[complement]: \(dictionary[complement] ?? 666)")
if let complementIndex = dictionary[complement] {
// print("RETURN")
return [complementIndex, index]
}
dictionary[value] = index
// print("POSTASSIGN dictionary: \(dictionary)")
}
return [Int]()
}
}
var tester = Solution()
// Testcase 1
tester.twoSum([2,7,11,15], 9) // Returns [0, 1]
// Testcase 2
tester.twoSum([3,2,4], 6) // Returns [1, 2]
// Testcase 3
tester.twoSum([3,3], 6) // Returns [0, 1]
// Testcase 4
tester.twoSum([9,8,7,6,0,2,4], 4) // Returns [4, 6]
// Testcase 5
tester.twoSum([0,1,2,3,4], 100) // Returns []
// End of problem and solution.


