题目
- 一个列表在空间复杂度为O(1)的情况下进行去重,要求去重后里面元素顺序不改变
- 原题
- 无序列表去重并保持原来顺序
- 空间复杂度为O(1)
list_num = [7, 2, 2, 3, 1, 2, 5, 1, 6, 4, 3, 7] -> [7, 2, 3, 1, 5, 6, 4]
解题思路分析
- 首先我们发现有两个限制条件:1.保持原来顺序 2.空间复杂度为O(1)
- 需求是去重
从以上两个限制可以看出来,我们使用 set 集合方式是不行,新建一个新列表装数据也不行,只能在原来的列表上进行操作
代码实现
"""
实现思路:1.通过多重循环列表里面的元素
2.一重遍历列表
3.二重判断当前遍历元素后面是否存在重复元素,存在时移除
"""
def list_to_repeat(_list: list):
if not isinstance(_list, list): # 判断传入是否为列表
raise Exception("传入的{}不是列表".format(_list))
if len(_list) < 2: # 判断列表是否为空或者一个元素,是,直接返回,不需要进行去重
return _list
else:
for nums in _list:
if not isinstance(nums, int):
raise Exception("列表里面存在非int整数,数据 {} 为 {} 类型".format(nums, type(nums)))
i = _list.index(nums) + 1
while i < len(_list):
if i >= len(_list):
break
elif _list[i] == nums:
_list.pop(i)
i = i -1
else:
pass
i = i + 1
return _list
"""
简单的进行测试
1. _list = [7, 2, 2, 3, 1, 2, 5, 1, 6, 4, 3, 7]
2. _list = "111"
3. _list = []
4. _list = [1]
5. -list = [1,1,1,1,1,1]
6. -list = [2,1,1,1,1,1,1]
7. -list = [1,1,1,[1],1,1]
8. -list = [2,1,1,3,"4",5]
"""
# 结果都是没有问题
以上为内容纯属个人理解,如有不足,欢迎各位大神指正,转载请注明出处!
如果觉得文章不错,欢迎关注微信公众号,微信公众号每天优先推送相关测试技术文章