-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.swift
66 lines (58 loc) · 1.45 KB
/
main.swift
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//
// main.swift
// LeetCode
//
// Created by Nihad on 11/17/21.
//
import Foundation
// MARK: - O(n)
func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
var dict = [Int: Int]()
for i in 0..<nums.count {
let complement = target - nums[i]
if dict.keys.contains(complement) {
return [dict[complement]!, i]
}
dict[nums[i]] = i
}
return []
}
// MARK: - O(nLogn)
//func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// let sortedNums = nums.sorted()
// var leftCaretIndex = 0
// var rightCaretIndex = sortedNums.count - 1
//
// if leftCaretIndex == rightCaretIndex {
// return [leftCaretIndex, rightCaretIndex]
// }
//
// for _ in 0..<sortedNums.count {
// guard leftCaretIndex != rightCaretIndex else {
// return []
// }
//
// if sortedNums[leftCaretIndex] + sortedNums[rightCaretIndex] == target {
// return [leftCaretIndex, rightCaretIndex]
// }
//
// if sortedNums[leftCaretIndex] + sortedNums[rightCaretIndex] < target {
// leftCaretIndex += 1
// } else {
// rightCaretIndex -= 1
// }
// }
//
// return []
//}
// MARK: - O^2
//func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
// for i in 0..<nums.count {
// for j in i+1..<nums.count {
// if nums[i] + nums[j] == target {
// return [i, j]
// }
// }
// }
// return []
//}