zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    javascript ajax 脚本跨域调用全解析
    [转载]linux sed命令详解
    perl随记(1)
    TCL随记(2)
    TCL随记(1)
    C Shell 中的特殊变量
    异步FIFO为什么用格雷码
    VMM学习-vmm_log
    UVM基础之---Command-line Processor
    Verification Mind Games---how to think like a verifier像验证工程师一样思考
  • 原文地址:https://www.cnblogs.com/seyjs/p/10016970.html
Copyright © 2011-2022 走看看