-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path945.minimum-increment-to-make-array-unique.0.cpp
68 lines (68 loc) · 1.28 KB
/
945.minimum-increment-to-make-array-unique.0.cpp
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
* @lc app=leetcode id=945 lang=cpp
*
* [945] Minimum Increment to Make Array Unique
*
* https://leetcode.com/problems/minimum-increment-to-make-array-unique/description/
*
* algorithms
* Medium (43.31%)
* Total Accepted: 12.2K
* Total Submissions: 28.3K
* Testcase Example: '[1,2,2]'
*
* 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
*
*
*
*
*
*/
class Solution {
public:
int minIncrementForUnique(vector<int>& A) {
int n = A.size();
int ans = 0;
sort(A.begin(), A.end());
for(int i=0; i+1<n; i++){
if(A[i]+1 <= A[i+1])
continue;
ans += A[i]+1-A[i+1];
A[i+1] = A[i]+1;
}
return ans;
}
};