Java解决方案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;
}
实际上,我们不需要将计数加一。我们可以简单地执行以下操作:
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;
}
时间为O(Nlog(N))。
Java解决方案2
我们首先使用存储桶数组对数字进行计数。对于每个存储桶,如果有多个存储桶,我们将其记录下来,当得到一个空存储桶时,将其放置在此处。
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;
}
时间为O(N),空间为O(N)。