param { number [ ] } arr param { number } k param { number } x function FindClosestElements ( arr , k , x ) { let left = 0 ; let right = arr . length - 1 ; let mid ; while ( left < right ) { mid = Math . floor ( left + ( right - left ) / 2 ) ; if ( arr [ mid ] === x ) { k -- ; break ; } else if ( arr [ mid ] < x && arr [ mid + 1 ] > x ) { x - arr [ mid ] > arr [ mid + 1 ] - x ? mid = mid + 1 : mid = mid ; k -- ; break ; } else if ( arr [ mid ] < x ) { left = mid + 1 ; } else { right = mid ; } } if ( left !== right ) { let pointerL = mid ; let pointerR = mid ; while ( k > 0 ) { if ( x - arr [ pointerL - 1 ] <= arr [ pointerR + 1 ] - x ) { if ( pointerL > 0 ) { pointerL -- ; k -- ; } else if ( k > 0 && pointerR < arr . length - 1 ) { pointerR ++ ; k -- ; } } else { if ( k > 0 && pointerR < arr . length - 1 ) { pointerR ++ ; k -- ; } else if ( pointerL > 0 ) { pointerL -- ; k -- ; } } } return arr . slice ( pointerL , pointerR + 1 ) ; } else { if ( left === 0 ) { return arr . slice ( 0 , k ) ; } else { return arr . slice ( arr . length - k ) ; } } } export { FindClosestElements } ;