Created
May 17, 2018 12:40
-
-
Save Albinzr/280b8ab5866ffa197eb524cee17f72d8 to your computer and use it in GitHub Desktop.
Find smallest +ve missing from array in swift
This file contains hidden or 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
import Foundation | |
var a = [1, 3, 6, 4, 1, 2] | |
var b = [1,2,3] | |
var c = [-1,-2,-3] | |
func findNearestMissingSmallValue(numberArray:[Int]) -> Int{ | |
var b = numberArray.sorted() | |
var smallestValue:Int? | |
for (i,v) in b.enumerated(){ | |
if i+1 <= b.count{ | |
if i - i+1 > 0{ | |
if !(b.contains(v+1)) && v+1 > 0{ | |
smallestValue = v+1 | |
break | |
} | |
} | |
} | |
if b[0] > 1{ | |
smallestValue = b[0] - 1 | |
}else if b.last! > 0 { | |
smallestValue = b.last! + 1 | |
} | |
} | |
guard let returnNumber = smallestValue else{ | |
//no possoble number | |
return 1 | |
} | |
return returnNumber | |
} | |
print(findNearestMissingSmallValue(numberArray: a)) | |
print(findNearestMissingSmallValue(numberArray: b)) | |
print(findNearestMissingSmallValue(numberArray: c)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment