LeetCode #945 - Minimum Increment to Make Array Unique

本文探讨了一种算法,旨在通过最少的步骤使数组中所有整数变得唯一。通过排序和增量调整策略,该算法有效地解决了问题,避免了数组元素间的重复。举例说明了如何将数组[1,2,2]转换为[1,2,3]只需一步,以及更复杂场景下所需步骤的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Given an array of integers A, a move consists of choosing any A[i], and incrementing it by 1.

Return the least number of moves to make every value in A unique.

Example 1:

Input: [1,2,2]

Output: 1

Explanation:  After 1 move, the array could be [1, 2, 3].

Example 2:

Input: [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.

Note:

1. 0 <= A.length <= 40000

2. 0 <= A[i] < 40000

class Solution {
public:
    int minIncrementForUnique(vector<int>& A) {
        sort(A.begin(),A.end()); //必须先排序
        int result=0;
        int pre=-1;//上一个元素加完之后的数值,下一个元素至少要加到pre+1
        for(int i:A)
        {
            if(i>pre) pre=i; //当前元素不会和pre冲突,不需要增加
            else
            {   //i需要加到等于pre+1
                result+=pre+1-i;
                pre++;
            }
        }
        return result;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值