Find K Closest Elements
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> result = new ArrayList<>(k);
int position = Arrays.binarySearch(arr, x);
int left;
int right;
if(position < 0){
position = -position - 1;
left = position - 1;
right = position;
}
else{
left = position - 1;
right = position + 1;
}
while(right - left - 1 != k){
if(left < 0){
right ++;
}
else if(right > arr.length - 1){
left --;
}
else if(arr[right] - x < x - arr[left]){
right ++;
}else{
left --;
}
}
for(int i = 0; i < k; i ++){
result.add(arr[left + i + 1]);
}
return result;
}
}
class Solution:
def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
result = [None]*k
if len(arr)==k:
return arr
if arr[0]>x:
for i in range(k):
result[i]= arr[i]
if arr[len(arr)-1]<x:
c=0
for i in range(len(arr)-1,0,-1):
if c < k:
result[i-1]=arr[i]
c+=1
else:
break
if arr[len(arr)-1]>=x:
index = binary_search_index(arr,x)
if index < 0:
index = -index -1
low, high = max([0, index-k-1]), min(len(arr)-1,index+k-1)
while (high-low)>(k-1):
if low < 0 or (x-arr[low])<=(arr[high]-x):
high-=1
elif (high > len(arr)-1) or (x-arr[low])>(arr[high]-x):
low+=1
return arr[low:high+1]
return result
def binary_search_index(arr, num, start=None, end=None):
if start is None and end is None:
start = 0
end = len(arr)
mid = start + ((end-start)//2)
a = arr[start:end]
if len(arr[start:end]) < 2:
return mid
if arr[mid] == num:
return mid
else:
if num < arr[mid]:
return binary_search_index(arr, num, start, mid-1)
if num > arr[mid]:
return binary_search_index(arr, num, mid+1, end)
最后更新于
这有帮助吗?