[Swift Weekly Contest 112]LeetCode945. 使数组唯一的最小增量 | 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.

 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:

  1. 0 <= A.length <= 40000
  2. 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 操作是不能让数组的每个值唯一的。

提示:

  1. 0 <= A.length <= 40000
  2. 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 }
 
 

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10015200.html