658. 找到 K 个最接近的元素
Java代码:滑窗
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] - x;
}
for(int i = 0; i < k; i++) {
list.add(arr[i] + x);
}
for (int i = k; i < arr.length; i++) {
if (Math.abs(arr[i]) < Math.abs(arr[i - k])) {
list.remove(new Integer(arr[i - k] + x)); // 如果入参是int类型,默认删除下边;
list.add(arr[i] + x);
}
}
return list;
}
}
java: 排序
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> list = new ArrayList<Integer>();
for (int num : arr) {
list.add(num);
}
Collections.sort(list, (a, b) -> {
if (Math.abs(a - x) != Math.abs(b - x)) {
return Math.abs(a - x) - Math.abs(b - x);
} else {
return a - b;
}
});
List<Integer> ans = list.subList(0, k);
Collections.sort(ans);
return ans;
}
}