Minimum Increment to Make Array Unique

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.
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.

思路:sort之后,相同的数排列在一起,A[i] 至少应该是前面数+1, 那么step = Math.max(A[i-1] + 1, A[i]),  A[i] 变成need;再往后计算;1,3是可以的。2 < 3, 3不变;1,1,后面的1是要变成2的;

class Solution {
    public int minIncrementForUnique(int[] A) {
        if(A == null || A.length == 0) {
            return 0;
        }
        Arrays.sort(A);
        int step = 0;
        int need = 0;
        for(int i = 1; i < A.length; i++) {
            need = Math.max(A[i - 1] + 1, A[i]);
            step += need - A[i];
            A[i] = need;
        }
        return step;
    }
}
发布了663 篇原创文章 · 获赞 13 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/105172847