-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwoSumProblem.swift
More file actions
44 lines (37 loc) · 893 Bytes
/
Copy pathTwoSumProblem.swift
File metadata and controls
44 lines (37 loc) · 893 Bytes
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
//
// TwoSumProblem.swift
// Algorithms With Swift
//
// Created by Akshansh Thakur on 21/08/20.
// Copyright © 2020 Akshansh Thakur. All rights reserved.
//
// Approch 1
func checkTwoSum(array: [Int], sum: Int) -> (Bool, Int?, Int?) {
var i = 0
var j = array.count - 1
while j > i {
switch array[i] + array[j] {
case (sum + 1)..<Int.max:
j -= 1
case Int.min..<sum:
i += 1
case sum:
return (true, array[i], array[j])
default:
return (false, nil, nil)
}
}
return (false, nil, nil)
}
// Approch 2
func checkTwoSum(array:[Int],sum:Int) -> (Bool,Int?,Int?){
var dic:[Int:Int] = [:]
for i in array{
if dic[i] != nil{
return (true,sum-i,i)
}else{
dic[sum-i] = i
}
}
return (false,nil,nil)
}