Last active
April 23, 2019 22:27
-
-
Save orkoden/55b5cbc9fb1d29cc496b92e886ee23dd to your computer and use it in GitHub Desktop.
swift solution to codility demo task
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
// MissingInteger | |
// Find the smallest positive integer that does not occur in a given sequence. | |
//This is a demo task. | |
// | |
//Write a function: | |
// | |
//public func solution(_ A : inout [Int]) -> Int | |
// | |
//that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. | |
// | |
//For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. | |
// | |
//Given A = [1, 2, 3], the function should return 4. | |
// | |
//Given A = [−1, −3], the function should return 1. | |
// | |
//Write an efficient algorithm for the following assumptions: | |
// | |
//N is an integer within the range [1..100,000]; | |
//each element of array A is an integer within the range [−1,000,000..1,000,000]. | |
// | |
let A = [1, 3, 6, 4, 1, 2] | |
let A2 = [1, 2, 3] | |
let A3 = [-1, -3] | |
public func solution(_ a : [Int]) -> Int { | |
let noNegative = a.filter { $0 > 0 } | |
let uniqueNumbers = Set(noNegative) | |
var uniqueArray = Array(uniqueNumbers) | |
uniqueArray.sort() | |
for (index, number) in uniqueArray.enumerated() { | |
if number > index + 1 { | |
return index + 1 | |
} | |
} | |
let largestIntNotPresent = (uniqueArray.last ?? 0) + 1 | |
return largestIntNotPresent | |
} | |
let a = solution(A) | |
let a2 = solution(A2) | |
let a3 = solution(A3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment