Last active
February 18, 2018 21:07
-
-
Save ernestlv/09b80b334f19b6e6a7f41ff1efec8a58 to your computer and use it in GitHub Desktop.
find smallest integer
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
function smallInt(A) { | |
let s = 1; | |
A.sort((a, b) => a - b) | |
if (A[0] >= 0) { | |
if (A.indexOf(1) === -1) { | |
return 1; | |
} | |
} | |
for (i=0; i<A.length; i++){ | |
s = A[i]+1; | |
s = s <= 0 ? 1 : s | |
if (A.indexOf(s) === -1) break; | |
} | |
return s; | |
} | |
//Version below ins in O(N) | |
function solution(A) { | |
A.sort((a, b) => a - b) | |
if (A[A.length-1] < 1) return 1; | |
if (A[A.length-1] === 1) return 2; | |
if (A[0] > 1) return 1; | |
var x = A.indexOf(1); | |
if (x === -1) return 1; | |
A = A.slice(x); | |
for (i=0; i<A.length-1;i++){ | |
if (A[i+1] - A[i] > 1){ | |
var s = A[i] + 1; | |
if (s < 1) return 1; | |
else return s; | |
} | |
} | |
return A[A.length-1]+1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment