【LeetCode】Easy: Two Sum
Two Sum
https://leetcode.com/problems/two-sum/
自分の回答
Swift Runtime: 12 ms
class Solution { func twoSum(_ nums: [Int], _ target: Int) -> [Int] { let dic = Dictionary<Int, Int>(uniqueKeysWithValues: nums.enumerated().map{($0, $1)}) for (i, num) in nums.enumerated() { if dic.values.contains(target - num) { let j = dic.filter {$0.value == (target - num)}.keys.first! return [i,j] } } fatalError() } }
回答例
https://leetcode.com/problems/two-sum/solution/
- JavaScript の回答がなるほどと思った
const twoSum = function(nums, target) { const comp = {}; for(let i=0; i<nums.length; i++){ if(comp[ nums[i] ] >= 0){ return [ comp[ nums[i] ] , i] } comp[ target-nums[i] ] = i } };
回答例を見て修正
class Solution { func twoSum(_ nums: [Int], _ target: Int) -> [Int] { var dic = Dictionary<Int, Int>() for (i, num) in nums.enumerated() { if let j = dic[target - num] { return [i,j] } dic[num] = i } fatalError("No two sum solution") } }
感想
- ヒントを見て、
Dictionary
を使うとこまではわかった。 Dictionary
の Key に与えられた数字を入れていくのは、そういうケースがなかったからか発想できなかった。- 回答例を実行すると 0ms で実行されるのだが、もっと早くなるのだろうか…
参考
Swift - SwiftのDictionary型でkeyを取り出す方法|teratail
let a = [ "apple": 100, "orange": 200, "banana": 100, ] print(Array(a.filter {$0.value == 100}.keys)) //=> ["banana", "apple"]
functional programming - Convert Swift Array to Dictionary with indexes - Stack Overflow
Xcode 9 - 10 • Swift 4.0 - 4.2
Using Swift 4 reduce(into:) method:
extension Collection { var indexedDictionary: [String: Element] { return enumerated().reduce(into: [:]) { $0[String($1.offset)] = $1.element } } }
Using Swift 4 Dictionary(uniqueKeysWithValues:) initializer and passing a new array from the enumerated collection:
extension Collection { var indexedDictionary: [String: Element] { return Dictionary(uniqueKeysWithValues: enumerated().map{(String($0),$1)}) } }