Skip to content

Commit

Permalink
001_Two_Sum
Browse files Browse the repository at this point in the history
  • Loading branch information
Di Wu committed Feb 12, 2015
0 parents commit e8e3fb0
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.DS_Store
7 changes: 7 additions & 0 deletions 001_Two_Sum.playground/contents.xcplayground
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='3.0' sdk='iphonesimulator'>
<sections>
<code source-file-name='section-1.swift'/>
</sections>
<timeline fileName='timeline.xctimeline'/>
</playground>
44 changes: 44 additions & 0 deletions 001_Two_Sum.playground/section-1.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
https://oj.leetcode.com/problems/two-sum/
#1 Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
Inspired by @naveed.zafar at https://oj.leetcode.com/discuss/10947/accepted-c-o-n-solution
*/

import Foundation

// O(N)
func twoSum(numbers: Array<Int>, target: Int) -> Array<Int> {
var hashMap: Dictionary = Dictionary<Int, Int>()
var result: Array = Array<Int>()

for i in 0..<numbers.count {
var numberToFind: Int = target - numbers[i]
if let numberToFindIndex = hashMap[numberToFind]? {
result.append(numberToFindIndex + 1)
result.append(i + 1)
return result
} else {
hashMap[numbers[i]] = i
}
}
return result
}

// test cases
twoSum([2, 7, 11, 15], 9)
twoSum([5, 5], 10)


6 changes: 6 additions & 0 deletions 001_Two_Sum.playground/timeline.xctimeline
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Timeline
version = "3.0">
<TimelineItems>
</TimelineItems>
</Timeline>

0 comments on commit e8e3fb0

Please sign in to comment.