LeetCode每日一题(945. Minimum Increment to Make Array Unique)

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
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值