Skip to content

Commit a0781b7

Browse files
committed
1. Two Sum
1 parent 19c6cb6 commit a0781b7

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

SwiftyLeetCode.playground/Contents.swift

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,44 @@
1-
//: Playground - noun: a place where people can play
1+
// Leetcode solutions in Swift.
2+
// Some solutions are from:
3+
// https://github.com/soapyigu/LeetCode_Swift
24

35
import UIKit
46

57
class Solution {}
68

9+
/**
10+
* 1. Two Sum
11+
* https://leetcode.com/problems/two-sum/
12+
*/
13+
14+
extension Solution {
15+
class func twoSum(nums: [Int], _ target: Int) -> [Int] {
16+
17+
guard nums.count > 1 else { return [] }
18+
19+
var map = [Int:Int]()
20+
21+
for i in 0..<nums.count {
22+
if let value = map[nums[i]] {
23+
return [value + 1, i + 1]
24+
}
25+
26+
map[target - nums[i]] = i
27+
}
28+
29+
return []
30+
}
31+
}
32+
33+
/*:
34+
### Usage
35+
*/
36+
37+
let twoSumNums = [2, 7, 11, 15]
38+
let target = 9
39+
40+
Solution.twoSum(nums: twoSumNums, target)
41+
742
/**
843
* 217. Contains Duplicate
944
* https://leetcode.com/problems/contains-duplicate/

0 commit comments

Comments
 (0)