Last active
September 4, 2018 08:49
-
-
Save loromits/170e14c42efe2d56e48e9766105797bb to your computer and use it in GitHub Desktop.
3SUM problem raw algorithm with O(n²) at worst
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Collection where Element: Comparable & Numeric { | |
typealias Triplet = (Element, Element, Element) | |
func threeSum() -> [Triplet] { | |
var result = [Triplet]() | |
let sortedSelf = sorted() | |
for (offset, a) in sortedSelf.dropLast().enumerated() { | |
var slice = sortedSelf.dropFirst(offset + 1) | |
while slice.count > 1, let b = slice.first, let c = slice.last { | |
if a + b + c == 0 { | |
result.append((a, b, c)) | |
slice = slice.dropFirst().dropLast() | |
} else if a + b + c > 0 { | |
slice = slice.dropLast() | |
} else { | |
slice = slice.dropFirst() | |
} | |
} | |
} | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment