【问题标题】:Contract m-repeated numbers in list to n-repeated (n<m) in place in O(1) space将列表中的 m 次重复数字收缩到 O(1) 空间中的 n 次重复 (n<m)
【发布时间】:2020-11-20 15:51:06
【问题描述】:

我想编写一个python 3.7 函数,它有一个排序的数字列表作为输入,一个数字n 是每个整数可以重复的最大数,并就地修改列表,所以任何重复超过n 次的数字,将被削减为n 重复,并且应该在O(1) 空间中完成,不允许额外的数据结构(例如set())。特殊情况 - 删除 n = 1 的重复项。示例:

dup_list = [1, 1, 1, 2, 3, 7, 7, 7, 7, 12]
dedup(dup_list, n = 1)
print(dup_list)
[1, 2, 3, 7, 12]

dup_list = [1, 1, 1, 2, 3, 7, 7, 7, 7, 12]
dedup(dup_list, n = 2)
print(dup_list)
[1, 1, 2, 3, 7, 7, 12]

dup_list = [1, 1, 1, 2, 3, 7, 7, 7, 7, 12]
dedup(dup_list, n = 3)
print(dup_list)
[1, 1, 1, 2, 3, 7, 7, 7, 12]

案例n = 1很简单,代码如下(代码取自Elements of Prograqmming Interviews, 2008, page 49,最后一行return dup_list[:write_index]除外):

def dedup(dup_list):                                                                                                       
    if not dup_list:                                                                                                       
        return 0                                                                                                           
                                                                                                                           
    write_index = 1                                                                                                        
    for i in range(1, len(dup_list)):                                                                                      
        if dup_list[write_index-1] != dup_list[i]:                                                                         
            dup_list[write_index] = dup_list[i]                                                                            
            write_index += 1                                                                                               
                                                                                                                           
    return dup_list[:write_index] 

【问题讨论】:

    标签: python-3.7 array-algorithms


    【解决方案1】:

    这应该可行:

    def dedup2(dup_list, n):
        count = 1
        list_len = len(dup_list)
        i = 1
        while i < list_len:
            if dup_list[i - 1] != dup_list[i]:
                count = 1
            else:
                count += 1
                if count > n:
                    del(dup_list[i])
                    i -= 1
                    list_len -= 1
            i += 1
        return dup_list
    
    print(dedup2([1, 2, 3, 3, 4, 4, 5, 5, 5, 5, 8, 9], 1))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多