LeetCode 题解工作台
使数组唯一的最小增量
给你一个整数数组 nums 。每次 move 操作将会选择任意一个满足 0 的下标 i ,并将 nums[i] 递增 1 。 返回使 nums 中的每个值都变成唯一的所需要的最少操作次数。 生成的测试用例保证答案在 32 位整数范围内。 示例 1: 输入: nums = [1,2,2] 输出: 1 …
4
题型
5
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们首先对数组 进行排序,用一个变量 记录当前的最大值,初始时 $\textit{y} = -1$。 然后遍历数组 ,对于每个元素 ,我们将 更新为 $\max(y + 1, x)$,并将操作次数 $y - x$ 累加到结果中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个整数数组 nums 。每次 move 操作将会选择任意一个满足 0 <= i < nums.length 的下标 i,并将 nums[i] 递增 1。
返回使 nums 中的每个值都变成唯一的所需要的最少操作次数。
生成的测试用例保证答案在 32 位整数范围内。
示例 1:
输入:nums = [1,2,2] 输出:1 解释:经过一次 move 操作,数组将变为 [1, 2, 3]。
示例 2:
输入:nums = [3,2,1,2,1,7] 输出:6 解释:经过 6 次 move 操作,数组将变为 [3, 4, 1, 2, 5, 7]。 可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。
提示:
1 <= nums.length <= 1050 <= nums[i] <= 105
解题思路
方法一:排序 + 贪心
我们首先对数组 进行排序,用一个变量 记录当前的最大值,初始时 。
然后遍历数组 ,对于每个元素 ,我们将 更新为 ,并将操作次数 累加到结果中。
遍历完成后,返回结果即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def minIncrementForUnique(self, nums: List[int]) -> int:
nums.sort()
ans, y = 0, -1
for x in nums:
y = max(y + 1, x)
ans += y - x
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n+max) |
| 空间 | O(n+max) |
面试官常问的追问
外企场景- question_mark
Assess the candidate's understanding of greedy algorithms and sorting strategies.
- question_mark
Test if the candidate can efficiently track uniqueness in large arrays.
- question_mark
Evaluate the candidate’s ability to implement efficient validation methods with minimal operations.
常见陷阱
外企场景- error
Not sorting the array before applying the greedy strategy.
- error
Failing to validate uniqueness efficiently, leading to redundant checks or incorrect results.
- error
Incorrectly handling edge cases, such as when no increments are needed or when the array has duplicate values at the start.
进阶变体
外企场景- arrow_right_alt
What if you needed to make the array unique by using both increments and decrements? How would the solution change?
- arrow_right_alt
If the array could contain negative numbers, how would you modify the approach to ensure uniqueness?
- arrow_right_alt
How would you approach this problem if you had to minimize both the number of moves and the final array sum?