【leetcode】945. 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

解题思路:本题的解法类似贪心算法。首先找出所有重复的值并且按升序排好,对于每个重复的值,都找出最小的并且大于自身以及当前不与其他值重复的值,两者的差值即为move的步数。

代码如下:

class Solution(object):
    def minIncrementForUnique(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        dic = {}
        dup = []
        for i in A:
            if i in dic:
                dup.append(i)
            else:
                dic[i] = 1
        dup.sort()
        res = 0
        current = 0
        for i in dup:
            current = max(i+1,current)
            while True:
                if current in dic:
                    current += 1
                    continue
                dic[current] = 1
                res += (current - i)
                current += 1
                break
        return res

 

posted @ 2018-11-25 20:05  seyjs  阅读(307)  评论(0编辑  收藏  举报