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].
/* 定义一个move 为选中一个元素+1
* 求最少多少move使数组中没有重复元素
* 1 2 2 2 3
* pre
* 1 2 3 4 5
* 排序
* 用pre记录当前数之前的值 如果pre<=A[i] 说明要
* */
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
if(A.empty()) return 0;
sort(A.begin(), A.end());
int move=0, pre=A[0], len = A.size();
for(int i=1;i<len;i++){
if(A[i] <= pre){
move += pre-A[i]+1;
pre++; //eg: 1 2 2 处理到第二个2时, pre=2, move=1, 2+1=3,同时pre进行+1
}
else{
pre = A[i];
}
}
return move;
}
};