[leetcode]945. Minimum Increment to Make Array Unique

版权声明:本文由lianyhai编写,不得用于商业用途,其他用途请随便。如果非要用做商业用途请给我微信打一下钱谢谢!哈哈哈哈 https://blog.csdn.net/qq_36303521/article/details/89045162

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.

作为一个菜鸟先上来就是 暴力解法

class Solution:
    def minIncrementForUnique(self, A: List[int]) -> int:
        if len(A)==0:
                return 0

        ans=0
        def check(num,k,A):
            B=A.copy()
            n=len(set(B))
            B[k]=B[k]+num
            if len(set(B)) > n:
                return True
            else: return False
        i=1
        while len(set(A)) < len(A):
            for j in range(len(A)):
                if check(i,j,A):
                    A[j]+=i
                    ans+=i
            i+=1

        return ans

毫无疑问,超时了,再想想有什么办法
一开始就想先排序,这样如果有重复的,就计算最小多少步可以达到不重复,那么就这样一直遍历完就ok了

class Solution:
    def minIncrementForUnique(self, A: List[int]) -> int:
        if not A: return 0
        n = len(A)
        ans,pre = 0,A[0]
        A.sort()
        for i in range(1,n):
            if A[i] <= pre:
                pre+=1
                ans+=pre-A[i]
            else:
                pre = A[i]
        return ans

猜你喜欢

转载自blog.csdn.net/qq_36303521/article/details/89045162