zoukankan      html  css  js  c++  java
  • leetcode刷题-945-使数组唯一的最小增量

    问题描述

    给定整数数组 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 字典存储元素及元素重复情况,重复的逐个进行计算

    A_len: A数组长度,用于遍历

    A_dic: 存储数组元素以及元素出现次数

    repeates: 存储有重复的元素

    repeate_done: 以完成递增操作的元素以及递增数值

    move_sum: 递增操作总次数

    将数组使用数据类型为字典的A_dic存储,数组元素对应key值,元素数量对应value值

    遍历A_dic中出现次数大于1的元素,将其放入到repeates中

    遍历repeates数组,开始进行递增操作,先检查是否已经进行过相同元素的操作,若有,则从上次相同元素的递增次数开始探测,若没有,则从该元素的下一位开始探测,若有空位,则move_sum加上探测成功的递增次数,若没有,继续进行下一位的探测,直至找到空位为止

    时间复杂度为O(n^2)

    def min_increament_for_unique(A):
        """
        hash存储,找相邻的空位置相加
        """
        A_len = len(A)
        A_dic = {}
        repeates = []
        repeate_done = {}
        move_sum = 0
    
        for i in range(A_len):
            if A[i] in A_dic:
                A_dic[A[i]] += 1
                repeates.append(A[i])
            else:
                A_dic[A[i]] = 1
    
        for x in repeates:
            done_flag = False
            
            if x in repeate_done:
                current_move_count = repeate_done[x]+1
            else:
                current_move_count = 1
            
            while not done_flag:
                if (x+current_move_count) not in A_dic:
                    A_dic[x+current_move_count] = 1
                    repeate_done[x] = current_move_count
                    move_sum += current_move_count
                    done_flag = True
                else:
                    current_move_count += 1
                    move_sum += 1
    
        return move_sum
    

  • 相关阅读:
    jsack
    生产BackPressure 的代码
    org.apache.flink.runtime.entrypoint.StandaloneSessionClusterEntrypoint
    https://www.callicoder.com/java-8-completablefuture-tutorial/
    microservices kubernetes
    flink metrics
    numRecordsIn 在哪里实现?
    flink Job提交过程
    https://jzh.12333sh.gov.cn/jzh/
    blocking
  • 原文地址:https://www.cnblogs.com/liuheblog/p/12296372.html
Copyright © 2011-2022 走看看