题目
- 使数组唯一的最小增量
给定整数数组 A,每次 move 操作将会选择任意 A[i],并将其递增 1。
返回使 A 中的每个值都是唯一的最少操作次数。
示例 1:
输入:[1,2,2]
输出:1
解释:经过一次 move 操作,数组将变为 [1, 2, 3]。
示例 2:
输入:[3,2,1,2,1,7]
输出:6
解释:经过 6 次 move 操作,数组将变为 [3, 4, 1, 2, 5, 7]。
可以看出 5 次或 5 次以下的 move 操作是不能让数组的每个值唯一的。
提示:
0 <= A.length <= 40000
0 <= A[i] < 40000
代码
class Solution {
public int minIncrementForUnique(int[] A) {
int ans=0;//先排序,然后用两个指针,一个找到元素重复的位置,另一个找到元素“断裂”(不连续)的位置
Arrays.sort(A);
/*for(int a:A)
System.out.print(a+" ");
System.out.println();*/
for(int pre=0,lat=pre+1;pre<A.length-1;) {
if(A[pre]==A[pre+1]){//找到重复元素位置为pre+1
for(lat=pre+1;lat<A.length-1;lat++) {
if((A[lat]+1)<A[lat+1]){//找到不连续位置为lat
break;
//然后需要前移元素,使得数组依然后续
}
}
int temp=A[lat]+1-A[pre+1];
ans+=temp;
int t=A[pre+1]+temp;
for(int j=pre+1;j<lat;j++) {//前移
A[j]=A[j+1];
}
A[lat]=t;
/*for(int a:A)
System.out.print(a+" ");
System.out.println();*/
}
//当pre和pre+1位置元素相等时,寻找后边的缺失元素,使pre位置元素增加然后调换位置
if(A[pre]!=A[pre+1])
pre++;
}
return ans;
}
}