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
  • 相关阅读:
    Solr4.8.0源码分析(12)之Lucene的索引文件(5)
    JAVA基础(1)之hashCode()
    Solr4.8.0源码分析(11)之Lucene的索引文件(4)
    检查数据不一致脚本
    索引的新理解
    数据库放到容器里
    动态规划
    每天晚上一个动态规划
    postgresql parallel join example
    名不正,则言不顺
  • 原文地址:https://www.cnblogs.com/seyjs/p/10016970.html
Copyright © 2011-2022 走看看