Given a sorted array, two integers k
and x
,
find the k
closest elements to x
in
the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3 Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1 Output: [1,2,3,4]
Note:
- The value k is positive and will always be smaller than the length of the sorted array.
- Length of the given array is positive and will not exceed 104
- Absolute value of elements in the array and x will not exceed 104
java
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
Comparator<Integer> cmp = new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
int d1 = Math.abs(a - x);
int d2 = Math.abs(b - x);
int diff = d2 - d1;
return diff;
}
};
Queue<Integer> queue = new PriorityQueue<>(k, cmp);
for (int i = 0; i < arr.length; i++) {
if (queue.size() < k) {
queue.offer(arr[i]);
} else {
int temp = queue.peek();
int v1 = Math.abs(temp - x);
int v2 = Math.abs(arr[i] - x);
if (v1 > v2) {
queue.poll();
queue.offer(arr[i]);
}
}
}
List<Integer> list = new ArrayList<>();
while(!queue.isEmpty()) {
list.add(queue.poll());
}
Collections.sort(list);
return list;
}
}