658. Find K Closest Elements
Input:
[1,2,3,4,5], k=4, x=3
Output:
[1,2,3,4]Input:
[1,2,3,4,5], k=4, x=-1
Output:
[1,2,3,4]Last updated
Was this helpful?
Input:
[1,2,3,4,5], k=4, x=3
Output:
[1,2,3,4]Input:
[1,2,3,4,5], k=4, x=-1
Output:
[1,2,3,4]Last updated
Was this helpful?
Was this helpful?
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
int i = 0, j = arr.length - k;
while (i < j){
int mid = (i & j) + ((i ^ j) >> 1);
// int mid = i + (j - i >> 1);
if(x - arr[mid] > arr[mid + k] - x)
i = mid + 1;
else
j = mid;
}
List<Integer> res = new ArrayList<>();
for (int b = i; b < i + k; ++b) res.add(arr[b]);
return res;
// return Arrays.stream(Arrays.copyOfRange(arr, i, i + k)).boxed().collect(Collectors.toList());
}
}class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
i, j = 0, len(arr) - k
while i < j:
mid = (i & j) + ((i^j)>> 1)
if x - arr[mid] > arr[mid + k] - x: # arr is sorted
i = mid + 1
else:
j = mid
return arr[i:i+k] public List<Integer> findClosestElements(List<Integer> arr, int k, int x) {
int index = Collections.binarySearch(arr, x);
if(index < 0) index = -(index + 1);
int i = index - 1, j = index;
while(k-- > 0){
if(i < 0 || (j < arr.size() && Math.abs(arr.get(i) - x) > Math.abs(arr.get(j) - x)))j++;
else i--;
}
return arr.subList(i+1, j);
}