Last active
October 10, 2017 00:55
-
-
Save evandocarmo/860e470542d2d66fb02b9670286b952f to your computer and use it in GitHub Desktop.
We'll call the consecutive distance rating of an integer sequence the sum of the distances between consecutive integers. Consider the sequence 1 7 2 11 8 34 3. 1 and 2 are consecutive integers, but their distance apart in the sequence is 2. 2 and 3 are consecutive integers, and their distance is 4. The distance between 7 and 8 is 3. The sum of t…
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
//O(n²) | |
function consecutiveDistance(arr) { | |
let total = 0; | |
for(let i = 0; i < array.length; i++) { | |
for(let j = i + 1; j < array.length; j++) { | |
if(arr[i] === arr[j] - 1 || arr[j] === arr[i] - 1) { | |
total += (j + 1) - (i + 1); | |
} | |
} | |
} | |
return total; | |
} | |
//Hashing -> O(2n) | |
function consecutiveDistanceHashing(arr) { | |
let total = 0; | |
let hash = []; | |
for(let i = 0; i < arr.length; i++) { | |
let number = arr[i]; | |
hash[number] = i; | |
} | |
for(let j = 0; j < arr.length; j++) { | |
let number = arr[j]; | |
if(hash[number - 1] && hash[number - 1] > j) { | |
total += hash[number - 1] - j; | |
} | |
if(hash[number + 1] && hash[number + 1] > j) { | |
total += hash[number + 1] - j; | |
} | |
} | |
return total; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment