【Leetcode】使数组唯一的最小增量(每日一题)

题目链接:使数组唯一的最小增量


题意:给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1

返回使 A 中的每个值都是唯一的最少操作次数。


题解:

1、暴力sort。O(nlogn)。排序以后,如果当前数字<=前一个数字,那么就把当前的数字变成前一个数字+1。

增量就是A[i-1]+1-A[i].遍历以后的结果就是要求的最小增量。跑了80ms

2、用一个数组表示hash。空间换时间。O(n)。

我们对hash数组进行移动操作,每次对hash[i]>1的数字进行操作,只保留一个数字,其余的加入到hash[i+1],因为移动增量是1,所以只要知道有多少个数字移动就可以了。这里给到40000了,所以总的hash数组可能到80000.这个跑了60ms


代码:

class Solution {
public:
    int minIncrementForUnique(vector<int>& A) {
        int len = A.size();
        sort(A.begin(),A.end());
        int ans = 0;
        for(int i = 1; i < len ;i++){
            if(A[i] <= A[i-1]){            
                ans += A[i-1]+1 - A[i];
                A[i] = A[i-1] + 1;
            }
        }
        return ans;
    }
};


OR


class Solution {
public:
    const int maxn = 80010;
    int minIncrementForUnique(vector<int>& A) {
        int len = A.size();
        int cnt[maxn] ={0};
        for(int i = 0; i < len ;i++){
            cnt[A[i]]++;
        }
        int ans = 0;
        for(int i = 0 ;i <= 80000;i++){
            if(cnt[i] > 1){
                ans += cnt[i] - 1;
                cnt[i+1] += cnt[i]-1;
                cnt[i] = 1;
            }
        }
        return ans;
    }
};

猜你喜欢

转载自www.cnblogs.com/Asumi/p/12549290.html