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:
0 <= A.length <= 40000
0 <= A[i] < 40000
Idea 1. Once the array is sorted, the next available number is at least a big as the previous + 1,
Time complexity: O(nlogn)
Space complexity: O(1), unless counting the space needed for sorting
1 class Solution { 2 public int minIncrementForUnique(int[] A) { 3 if(A.length == 0) { 4 return 0; 5 } 6 7 Arrays.sort(A); 8 int prev = A[0]; 9 int cnt = 0; 10 for(int i = 1; i < A.length; ++i) { 11 if(A[i] <= prev) { 12 cnt += prev - A[i] + 1; 13 prev += 1; 14 } 15 else { 16 prev = A[i]; 17 } 18 } 19 return cnt; 20 } 21 }
网上更简洁的方法,亮瞎眼啊
1 class Solution { 2 public int minIncrementForUnique(int[] A) { 3 if(A.length == 0) { 4 return 0; 5 } 6 7 Arrays.sort(A); 8 int nextAvailable = A[0] + 1; 9 int cnt = 0; 10 for(int i = 1; i < A.length; ++i) { 11 cnt += Math.max(nextAvailable - A[i], 0); 12 nextAvailable = Math.max(nextAvailable, A[i]) + 1; 13 } 14 return cnt; 15 } 16 }
Idea 2. Map + count, didn't get the limit of 10000 at first, then imagin n= 4, instead of 10000, [4, 4, 4, 4], the max would be max(A) + len(A) -1
Time complexity: O(n + max(A)), n = A.length
Space complexity: O(n + max(A))
1 class Solution { 2 public int minIncrementForUnique(int[] A) { 3 int n = A.length; 4 int[] count = new int[80000]; 5 6 for(int a: A) { 7 ++count[a]; 8 } 9 10 int result = 0; 11 int needed = 0; 12 for(int i = 0; i < 80000; ++i) { 13 if(count[i] >= 2) { 14 result -= (count[i]-1) * i; 15 needed += count[i] - 1; 16 } 17 else if(needed > 0 && count[i] == 0) { 18 --needed; 19 result += i; 20 } 21 } 22 23 return result; 24 } 25 }