Heaps Top K
411. Sort a Nearly Sorted Array
You are given an array of integers nums that is nearly sorted, and an integer k. Every element of nums
is at most k positions away from its place in the sorted array, to the left or to the right. Return nums
sorted from smallest to largest.
When a value appears more than once, its copies keep their order: the first copy belongs at the first of their places. The distance of each copy is measured that way.
You may sort nums itself and return it, or return a new array.
Example 1
Input: nums = [4, 2, 7, 3, 9, 5, 8], k = 2
[2,3,4,5,7,8,9]Explanation: The 3 sits at index 3 and belongs at index 1, two places to its left. The 9 sits at index 4 and belongs at index 6. No element is more than 2 places from where it belongs.
Example 2
Input: nums = [-3, -8, -8, 0, -1], k = 2
[-8,-8,-3,-1,0]Explanation: The −3 belongs at index 2, two places to its right. The two −8s belong at indexes 0 and 1, so each one moves one place to the left.
Example 3
Input: nums = [-1000000000, 6, 6, 1000000000], k = 0
[-1000000000,6,6,1000000000]Explanation: With k = 0 every element is already in its place.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1090 ≤ k < nums.length- Every element of
numsis at mostkpositions from its place in the sorted array.
Clarifying questions
What you would ask an interviewer before writing any code.