LeetCode 658. Find K Closest Elements(java)
阿新 • • 發佈:2018-12-30
Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.
Example 1:
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5 ], k=4, x=-1
Output: [1,2,3,4]
Note:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 104
Absolute value of elements in the array and x will not exceed 104
我的解法:類似於暴力解,時間複雜度很高,思路就是:二分找到x在數組裡的插入位置,再在數組裡的那個位置向左和向右看,每次加進去一個,直到加滿k個,這個方法不是很推薦,但是還是給個程式碼吧:
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> result = new ArrayList<>();
if (arr.length == 0) return result;
int index = findInsert(arr, x);
int count = 1, i = 1;
result.add(arr[index]);
int left = index - 1;
int right = index + 1;
while (count < k) {
if (left < 0) {
result.add(arr[right]);
right++;
count++;
} else if (right > arr.length - 1 || arr[right] - x >= x - arr[left]) {
result.add(0, arr[left]);
left--;
count++;
} else {
result.add(arr[right]);
right++;
count++;
}
}
return result;
}
public int findInsert(int[] arr, int x) {
int begin = 0;
int end = arr.length - 1;
while (begin < end) {
int mid = begin + (end - begin) / 2;
if (x == arr[mid]) {
return mid;
} else if (x > arr[mid]) {
begin = mid + 1;
} else {
end = mid - 1;
}
}
return begin;
}
解法二:這個解法是直接從數組裡通過二分法找到應為的subarray的start位置,通過判斷mid位置和mid + k位置上與x的差值的大小比較來確定二分的update rule,因此時間複雜度更好。
public List<Integer> findClosestElements(int[] arr, int k, int x) {
List<Integer> res = new ArrayList<>();
int start = 0, end = arr.length-k;
while(start<end){
int mid = start + (end-start)/2;
if(Math.abs(arr[mid]-x)>Math.abs(arr[mid+k]-x)){
start = mid+1;
} else {
end = mid;
}
}
for(int i=start; i<start+k; i++){
res.add(arr[i]);
}
return res;
}