Problem
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
Solution
Approach 1 : Counting
Intuition
Let's count the quantity of each element. Clearly, we want to increment duplicated values.
For each duplicate value, we could do a "brute force" solution of incrementing it repeatedly until it is not unique. However, we might do a lot of work - consider the work done by an array of all ones. We should think of how to amend our solution to solve this case as well.
What we can do instead is lazily evaluate our increments. If for example we have [1,1,1,1,3,5], we don't need to process all the increments of duplicated 1s. We could take three ones (taken= [1, 1, 1]) and continue processing. When we find an empty place like 2, 4, or 6, we can then recover that our increment will be 2-1, 4-1, and 6-1.
Algorithm
Count the values. For each possible value x :
•If there are 2 or more values x in A, save the extra duplicated values to increment later.
•If there are 0 values x in A, then a saved value v gets incremented to x.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class Solution: def minIncrementForUnique(self, A): """ :type A: List[int] :rtype: int """ n = len(A) if n < 2 : return 0 ans = 0 dup = [] count = collections.Counter(A) i = min(count) # 배열 내 가장 작은 수 end = max(count) while dup or i <= end : if count[i] >= 2 : dup.extend([i]*(count[i]-1)) elif dup and count[i] == 0: ans += i - dup.pop() i += 1 return ans | cs |
Complexity Analysis
•Time Complexity : \(O(N)\), where N is the length of A.
•Space Complexity : \(O(N)\).
Source
https://leetcode.com/problems/minimum-increment-to-make-array-unique/
'0 > algorithm' 카테고리의 다른 글
Minimum Depth of Binary Tree (in Python) (0) | 2019.01.29 |
---|---|
Sort linked list (in Python) (0) | 2019.01.27 |
Climbing Stairs (in Python) (0) | 2019.01.23 |
Add Binary (in Python) (0) | 2019.01.23 |
Rotate Image (in Python) (0) | 2019.01.23 |