forked from ecmadao/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo01.two-sum.swift
More file actions
53 lines (49 loc) · 1.53 KB
/
No01.two-sum.swift
File metadata and controls
53 lines (49 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* Difficulty:
* Easy
*
* Desc:
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
*
* Example:
* Given nums = [2, 7, 11, 15], target = 9,
* Because nums[0] + nums[1] = 2 + 7 = 9,
* return [0, 1]
*/
class Solution {
func twoSum_loop(_ nums: [Int], _ target: Int) -> [Int] {
var startIndex = nums.startIndex
while startIndex < nums.endIndex - 1 {
var endIndex = startIndex + 1
while endIndex <= nums.endIndex - 1 {
if nums[startIndex] + nums[endIndex] == target {
return [startIndex, endIndex]
} else {
endIndex += 1
}
}
startIndex += 1
}
return [Int]()
}
func twoSum_hashtable(_ nums: [Int], _ target: Int) -> [Int] {
var dict = Dictionary<Int, Array<Int>>()
for (index, value) in nums.enumerated() {
var arr = dict[value, default: []]
arr.append(index)
dict[value] = arr
}
for (index, value) in nums.enumerated() {
var remainder = target - value
guard let arr = dict[remainder] else {
continue
}
let result = arr.filter { i in i != index }
if result.count > 0 {
return [index, result[0]]
}
}
return [Int]()
}
}