945. Minimum Increment to Make Array Unique(Leetcode每日一题-2020.03.22)

Problem

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.

Note:

0 <= A.length <= 40000
0 <= A[i] < 40000

Example1

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

Example2

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.

Solution

一开始用的暴力法,map记录每个数的出现次数,set记录已经出现过的数。然后对于map中出现次数大于2的数,将其递增为set中没有的数。这种 O ( n 2 ) O(n^2) 的暴力法,必然超时了。

参照了官方解法。

class Solution {
public:
    int minIncrementForUnique(vector<int>& A) {
        //如果有40000个3999的话,就需要这么多的空间
        int count[80000] = {0};

        for(auto a:A)
            ++count[a];

        int repeatCnt = 0;;
        int ret = 0;
        for(int i = 0;i<80000;++i)
        {
            if(count[i] >=2)
            {
                repeatCnt += count[i] - 1;
                ret -= i * (count[i] - 1); //将重复的数都减小为0
            }
            else if(repeatCnt > 0 && count[i] == 0)//还有重复的数,且当前的数没有出现,就把一个0加到当前大小
            {
                repeatCnt--;
                ret += i;
            }
        }

        return ret;
    }
};
发布了507 篇原创文章 · 获赞 215 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/sjt091110317/article/details/105031201