题目描述:
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.
Example 1:
Input: [1,2,2]
Output: 1
Explanation: After 1 move, the array could be [1, 2, 3].
Example 2:
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.
Note:
1. 0 <= A.length <= 40000
2. 0 <= A[i] < 40000
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
sort(A.begin(),A.end()); //必须先排序
int result=0;
int pre=-1;//上一个元素加完之后的数值,下一个元素至少要加到pre+1
for(int i:A)
{
if(i>pre) pre=i; //当前元素不会和pre冲突,不需要增加
else
{ //i需要加到等于pre+1
result+=pre+1-i;
pre++;
}
}
return result;
}
};