LeetCode – Minimum Increment to Make Array Unique (Java)

Java Solution 1

public int minIncrementForUnique(int[] A) {
    Arrays.sort(A);
 
    int count = 0;
    for(int i=1; i<A.length; i++){
        if(A[i]<=A[i-1]){
            count+=A[i-1]+1;
            A[i]=A[i]+1;
        }
    }
 
    return count;
}

Actually we do not need to increment the count by one. We can simply do the following:

public int minIncrementForUnique(int[] A) {
    Arrays.sort(A);
 
    int count = 0;
    for(int i=1; i<A.length; i++){
        if(A[i]<=A[i-1]){
            count+=A[i-1]+1-A[i];
            A[i]=A[i-1]+1;
        }
    }
 
    return count;
}

Time is O(Nlog(N)).

Java Solution 2

we first count the number using a bucket array. For each bucket, if there are more than one, we record it and when get an empty bucket, put it there.

public int minIncrementForUnique(int[] A) {
    int result = 0;
 
    int[] count = new int[100000];
    for(int i: A){
        count[i]++;
    }
 
    int dup = 0;
    for(int i=0; i<100000; i++){
        if(count[i]>1){
            result -= (count[i]-1)*i;
            dup += count[i]-1;
        }else if(count[i]==0 && dup>0){
            result += i;
            dup--;
        }
    }
 
    return result;
}

Time is O(N) and space is O(N).

Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>