[Swift Weekly Contest 112]LeetCode945. 使陣列唯一的最小增量 | Minimum Increment to Make Array Unique
阿新 • • 發佈:2018-11-25
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
給定整數陣列 A,每次 move
A[i]
,並將其遞增 1
。
返回使 A
中的每個值都是唯一的最少操作次數。
示例 1:
輸入:[1,2,2] 輸出:1 解釋:經過一次 move 操作,陣列將變為 [1, 2, 3]。
示例 2:
輸入:[3,2,1,2,1,7] 輸出:6 解釋:經過 6 次 move 操作,陣列將變為 [3, 4, 1, 2, 5, 7]。 可以看出 5 次或 5 次以下的 move 操作是不能讓陣列的每個值唯一的。
提示:
0 <= A.length <= 40000
0 <= A[i] < 40000
508ms
1 class Solution { 2 func minIncrementForUnique(_ A: [Int]) -> Int { 3 var arr:[Int] = A.sorted(by:<) 4 var r:Int = -1 5 var ret:Int = 0 6 for i in 0..<arr.count 7 { 8 var to:Int = max(r,arr[i]) 9 ret += abs(to - arr[i]) 10 r = to + 1 11 } 12 return ret 13 } 14 }