Given a sorted integer array arr
, two integers k
and x
, return the k
closest integers to x
in the array. The result should also be sorted in ascending order.
An integer a
is closer to x
than an integer b
if:
|a - x| < |b - x|
, or|a - x| == |b - x|
anda < b
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3 Output: [1,2,3,4]
Example 2:
Input: arr = [1,2,3,4,5], k = 4, x = -1 Output: [1,2,3,4]
Constraints:
1 <= k <= arr.length
1 <= arr.length <= 104
arr
is sorted in ascending order.-104 <= arr[i], x <= 104
class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { List<Integer> list = new ArrayList(); for(int i : arr) list.add(i); Collections.sort(list, (a, b) -> Math.abs(a - x) - Math.abs(b - x)); List<Integer> res = list.subList(0, k); Collections.sort(res); return res; } }
! 就摁用API,先按要求把list排好序。。属实妹想到,然后要多少拿多少,再排一次序。
class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { int lo = 0, hi = arr.length - 1; while(hi - lo >= k) { if(Math.abs(arr[lo] - x) > Math.abs(arr[hi] - x)) lo++; else hi--; } List<Integer> res = new ArrayList(); for(int i = lo; i <= hi; i++) res.add(arr[i]); return res; } }
用two pointers可以达到O(n), 最终lo到hi就是答案