282. K Nearest Integers

Given an integer array arr and two integers k and x. Your task is to find k numbers from the array that are nearest to the value x. The nearness of a integer is determined by its absolute difference from x. If two integers have the same difference from x, choose the smaller integer. Return the selected integers sorted in ascending order.

Example 1:

Input: arr = [4, 1, 3, 2, 5], k = 3, x = 3

Output: [2, 3, 4]

Explanation: The integers nearest to 3 are 3 (distance 0), 2 (distance 1), and 4 (distance 1). After sorting, the result is [2, 3, 4].

Example 2:

Input: arr = [10, 5, 2, 1, 7], k = 4, x = 6

Output:[2, 5, 7, 10]

Explanation: The nearest integers to 6 are 5 (distance 1), 7 (distance 1), 10 (distance 4), and 2 (distance 4). After Sorting, the result is [2, 5, 7, 10].

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= k <= arr.length
  • 1 <= arr.length <= 104
  • -104 <= arr[i], x <= 104

Fun Facts

0
class Solution {
public:
vector<int> kNearestIntegers(vector<int>& arr, int k, int x) {
}
}
Test Case

Input:

Arr
K
X