By Long Luo

Here shows 4 Approaches to slove this problem: Two Pointers, Sorting, Priority Queue and Binary Search with Two Pointers.

# Two Pointers

## Analysis

• Time Complexity: $O(n + klogk)$.
• Space Complexity: $O(n)$.

# Sorting

## Analysis

• Time Complexity: $O(nlogn + klogk)$.
• Space Complexity: $O(n)$.

# Priority Queue

## Analysis

• Time Complexity: $O(nlogn+klogk)$
• Space Complexity: $O(n)$

# BinarySearch

Since the array is sorted, so it’s easy to use the Binary Search method to find the closest element of $\textit{x}$, then we start to find the other closest elements both the left and right.

The code is too obscure, we can just find the closest element which gt than $\textit{x}$, then use two pointers to search other $\textit{k}$ elements from both sides.

## Analysis

• Time Complexity: $O(logn + k)$.
• Space Complexity: $O(1)$

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗