Title Description
Given an array of integers A, select any operation will move each A [i], and increments its 1.
A return value of each of the minimum number of operations is unique.
Example 1:
Input: [1,2,2]
Output: 1
Explanation: Following a move operation, the array becomes [1, 2, 3].
Example 2:
Input: [3,2,1,2,1,7]
Output: 6
Explanation: after 6 move operation, the array becomes [3, 4, 1, 2, 5, 7].
The following can be seen five times or five times move operation is not possible for each unique value of the array.
prompt:
0 <= A.length <= 40000
0 <= A[i] < 40000
Problem-solving ideas
1.先排序
2.遍历数组,若当前元素小于等于它的前一个元素,则将其变为前一个数+1
3.复杂度O(nlogn)
code show as below
package leetcode;
import java.util.Arrays;
public class MinIncrementForUnique {
public int minIncrementForUnique(int[] A) {
int result=0;
Arrays.sort(A);
for (int i = 0; i < A.length; i++) {
if (A[i]<=A[i-1]) {
int pre=A[i];
A[i]=A[i-1]+1;
result+=A[i]-pre;
}
}
return result;
}
}