【发布时间】: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