658 Find K Closest Elements
1. Question
Given a sorted array, two integerskandx, find thekclosest elements toxin 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 10^4
Absolute value of elements in the array and x will not exceed 10^4
2. Implementation
(1) Binary Search + Two Pointers
思路: 这道题非常多corner cases要注意考虑
3. Time & Space Complexity
Binary Search + Two Pointers: 时间复杂度O(logn + k), 空间复杂度O(k)
Last updated
Was this helpful?