Created
February 16, 2021 07:45
-
-
Save MohammedALREAI/0c04fd3b93edfa85e6a4ec25e7dbf2e8 to your computer and use it in GitHub Desktop.
smallestDifference AlgoExport
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
function smallestDifference(arr1:Array<number>,arr2:Array<number>):Array<number>{ | |
arr1=arr1.sort((a,b)=>a-b) | |
arr2=arr2.sort((a,b)=>a-b) | |
let p1=0 | |
let p2=0 | |
let smallest = Infinity; | |
let current = Infinity; | |
let smallestPair:Array<number> = []; | |
while(p1<arr1.length && p2<arr2.length){ | |
let first=arr1[p1]; | |
let secand=arr2[p1]; | |
if(first<secand){ | |
current=secand-first | |
p1++ | |
} | |
else if(first>secand){ | |
current=first-secand | |
p2++ | |
} | |
else{ | |
return [first,secand] | |
} | |
if(smallest>current){ | |
smallest=current | |
smallestPair = [first, secand]; | |
} | |
} | |
return smallestPair | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment