You are given an integer array nums. In one move, you can pick an index i where 0 <= i < nums.length and increment nums[i] by 1.
Return the minimum number of moves to make every value in nums unique.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: nums = [1,2,2]
Output: 1
Explanation: After 1 move, the array could be [1, 2, 3].
Example 2:
Input: nums = [3,2,1,2,1,7]
Output: 6
Explanation: After 6 moves, the array could be [3, 4, 1, 2, 5, 7].
It can be shown with 5 or less moves that it is impossible for the array to have all unique values.
Constraints:
- 1 <= nums.length <= 105
- 0 <= nums[i] <= 105
看注释吧
use std::collections::HashMap;
impl Solution {
pub fn min_increment_for_unique(nums: Vec<i32>) -> i32 {
// 将nums转化为(num, count)的数组并且进行排序
let mut l: Vec<(i32, i32)> = nums
.into_iter()
.fold(HashMap::new(), |mut m, n| {
*m.entry(n).or_insert(0) += 1;
m
})
.into_iter()
.map(|(k, v)| (k, v))
.collect();
l.sort();
let mut stack = Vec::new();
let mut curr = l[0].0;
let mut i = 0;
let mut ans = 0;
while i < l.len() {
// 如果curr在l[i]中存在,证明此位置没有空位, 加载上当前位置多余的数字(count > 1)
if curr == l[i].0 {
if l[i].1 > 1 {
stack.push((l[i].0, l[i].1 - 1));
}
curr += 1;
i += 1;
continue;
}
// 如果curr在l[i]中不存在, 证明此位置可以放置一个多余的数字, 其移动的步数为curr - last_v, 注意, 我们无论从stack的左侧取值还是从右侧取值,对最终结果是不会有影响的
if let Some((last_v, last_c)) = stack.pop() {
ans += curr - last_v;
if last_c > 1 {
stack.push((last_v, last_c - 1));
}
}
curr += 1;
}
// 将剩余的数字放到尾部, 因为已经超过nums的最大值, 所以后面的curr都是空位
while let Some((v, c)) = stack.pop() {
ans += curr - v;
if c > 1 {
stack.push((v, c - 1));
}
curr += 1;
}
ans
}
}