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
Solution 1
Find the k closest elements to x <=> remove the (n-k) elements farthest from x. So using two points to point to left, right, then every time remove a further element, util k elements left.
Refer to http://www.cnblogs.com/grandyang/p/7519466.html
// C++
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int n = arr.size();
if (n <= 0 || k > n) {
return vector<int>();
}
int left = 0;
int right = n - 1;
while ((right - left + 1) > k) {
if (x - arr[left] <= arr[right] - x) {
--right;
} else {
++left;
}
}
return vector<int>(arr.begin() + left, arr.begin() + left + k);
}
""" Python """
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
n = len(arr)
if n <= 0 or k > n:
return []
# in python, don't need define, use variable directly
start = 0
end = n - 1
while (end - start + 1) > k:
if x - arr[start] <= arr[end] - x:
end -= 1
else:
start += 1
return arr[start: start + k]
Time Complexity: O(n - k)
Space Complexity: O(1)
Solution 2
Since the problem has a sorted array, it’s easy to consider binary search.
Step 1: find the first element who is less than x, return its index
Step 2: beginning with the index, comparing elements on both sides, add the closer element one by one, util to get k elements
// C++
""" python """
Solution 3
TODO