Class Solution
-
- All Implemented Interfaces:
public final class Solution2948 - Make Lexicographically Smallest Array by Swapping Elements\.
Medium
You are given a 0-indexed array of positive integers
numsand a positive integerlimit.In one operation, you can choose any two indices
iandjand swapnums[i]andnums[j]if|nums[i] - nums[j]| <= limit.Return the lexicographically smallest array that can be obtained by performing the operation any number of times.
An array
ais lexicographically smaller than an arraybif in the first position whereaandbdiffer, arrayahas an element that is less than the corresponding element inb. For example, the array[2,10,3]is lexicographically smaller than the array[10,2,3]because they differ at index0and2 < 10.Example 1:
Input: nums = 1,5,3,9,8, limit = 2
Output: 1,3,5,8,9
Explanation: Apply the operation 2 times:
Swap nums1 with nums2. The array becomes 1,3,5,9,8
Swap nums3 with nums4. The array becomes 1,3,5,8,9
We cannot obtain a lexicographically smaller array by applying any more operations.
Note that it may be possible to get the same result by doing different operations.
Example 2:
Input: nums = 1,7,6,18,2,1, limit = 3
Output: 1,6,7,18,1,2
Explanation: Apply the operation 3 times:
Swap nums1 with nums2. The array becomes 1,6,7,18,2,1
Swap nums0 with nums4. The array becomes 2,6,7,18,1,1
Swap nums0 with nums5. The array becomes 1,6,7,18,1,2
We cannot obtain a lexicographically smaller array by applying any more operations.
Example 3:
Input: nums = 1,7,28,19,10, limit = 3
Output: 1,7,28,19,10
Explanation: 1,7,28,19,10 is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices.
Constraints:
<code>1 <= nums.length <= 10<sup>5</sup></code>
<code>1 <= numsi<= 10<sup>9</sup></code>
<code>1 <= limit <= 10<sup>9</sup></code>
-
-
Constructor Summary
Constructors Constructor Description Solution()
-
Method Summary
Modifier and Type Method Description final IntArraylexicographicallySmallestArray(IntArray nums, Integer limit)-
-
Method Detail
-
lexicographicallySmallestArray
final IntArray lexicographicallySmallestArray(IntArray nums, Integer limit)
-
-
-
-