K Closest Values
nums is sorted in non-decreasing order. Return the k items of nums that are closest to target, as a list in non-decreasing order. The distance of an item x is abs(x - target).
An item a is preferred over an item b when a is closer to target, or when they are equally close and a < b; the answer holds the k most preferred items. Items with the same value count separately, so the answer can hold repeats. The chosen items always form a block of neighbours in nums.
Example 1
6 and 8 are 1 away from 7, and 10 is 3 away, closer than 3, which is 4 away.
Example 2
4 and 6 are closest; for the third spot 1 and 9 are both 4 away, and the smaller one, 1, wins.
Constraints
1 <= k <= len(nums) <= 100-1000 <= nums[i], target <= 1000numsis sorted in non-decreasing order
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Sorting and searching problems
- Kth Smallest Pair SumMedium
- Least Truck CapacityMedium
- Merge IntervalsMedium
- Rebuild the LineMedium
- Smallest Divisor Under a LimitMedium
- Spread the TentsMedium
- The One Without a TwinMedium
- The Slot That Comes NextMedium