Given target
, a non-negative integer k
and an integer array A
sorted in ascending order, find the k
closest numbers to target
in A
, sorted in ascending order by the difference between the number and target. Otherwise, sorted in ascending order by number if the difference is same.
Example
Example 1:
Input: A = [1, 2, 3], target = 2, k = 3
Output: [2, 1, 3]
Example 2:
Input: A = [1, 4, 6, 8], target = 3, k = 3
Output: [4, 1, 6]
Challenge
O(logn + k) time
思路:先找到起始start point,然后用打擂台的方法O(K)的去取得最近的值;
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> list = new LinkedList<>();
int index = findClosestIndex(arr, x);
list.add(arr[index]);
int count = 1;
int i = index - 1; int j = index + 1;
while(count < k) {
if(0 <= i && j < arr.length) {
if(x - arr[i] <= arr[j] - x) {
list.add(0, arr[i]);
i--;
} else {
list.add(arr[j]);
j++;
}
} else if(0 <= i && j >= arr.length) {
list.add(0, arr[i]);
i--;
} else if(i < 0 && j < arr.length) {
list.add(arr[j]);
j++;
}
count++;
}
return list;
}
public int findClosestIndex(int[] arr, int x) {
int start = 0; int end = arr.length - 1;
while(start + 1 < end) {
int mid = start + (end - start) / 2;
if(arr[mid] == x) {
return mid;
} else if(arr[mid] > x) {
end = mid;
} else {
// arr[mid] < x;
start = mid;
}
}
if(Math.abs(arr[start] - x) <= Math.abs(arr[end] - x)) {
return start;
}
return end;
}
}