|
| 1 | +# [945. Minimum Increment to Make Array Unique](https://leetcode.com/problems/minimum-increment-to-make-array-unique/) |
| 2 | + |
| 3 | +--- |
| 4 | +title: "Min Increment For Unique" |
| 5 | +summary: "This document provides a solution to the problem of finding the minimum number of increments required to make all elements in an array unique." |
| 6 | +date: "2024年06月14日" |
| 7 | +modifiedDate: "2024年06月14日" |
| 8 | +tags: ["Algorithm", "JavaScript", "Sorting", "Array"] |
| 9 | +slug: "min-increment-for-unique" |
| 10 | + |
| 11 | +--- |
| 12 | + |
| 13 | + |
| 14 | + |
| 15 | +## Intuition |
| 16 | + |
| 17 | +The first thought to solve this problem is to ensure that each element in the array is unique by incrementing the necessary elements. Sorting the array initially can help in easily identifying the elements that need to be incremented. |
| 18 | + |
| 19 | +## Approach |
| 20 | + |
| 21 | +1. Sort the array in ascending order. |
| 22 | +2. Iterate through the sorted array starting from the second element. |
| 23 | +3. For each element, check if it is less than or equal to the previous element. |
| 24 | +4. If it is, calculate the increment needed to make it one more than the previous element. |
| 25 | +5. Increment the element and add the increment count to the total moves. |
| 26 | +6. Continue this process until the end of the array. |
| 27 | +7. Return the total moves as the result. |
| 28 | + |
| 29 | +## Complexity |
| 30 | + |
| 31 | +- **Time complexity:** O(n log n) due to the sorting step. The subsequent iteration through the array is O(n), but the sorting dominates the overall time complexity. |
| 32 | + |
| 33 | +- **Space complexity:** O(1) as the sorting can be done in-place, and only a few extra variables are used. |
| 34 | + |
| 35 | +## Code |
| 36 | + |
| 37 | +```javascript |
| 38 | +/** |
| 39 | + * @param {number[]} nums |
| 40 | + * @return {number} |
| 41 | + */ |
| 42 | +function minIncrementForUnique(nums) { |
| 43 | + nums.sort((a, b) => a - b); |
| 44 | + |
| 45 | + let moves = 0; |
| 46 | + |
| 47 | + // Iterate through the sorted array |
| 48 | + for (let i = 1; i < nums.length; i++) { |
| 49 | + // If the current element is not greater than the previous one |
| 50 | + if (nums[i] <= nums[i - 1]) { |
| 51 | + // Calculate the number of moves needed to make it greater |
| 52 | + let increment = nums[i - 1] - nums[i] + 1; |
| 53 | + // Increment the current element |
| 54 | + nums[i] += increment; |
| 55 | + // Add the moves to the total count |
| 56 | + moves += increment; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return moves; |
| 61 | +} |
0 commit comments