编写算法,在一非递减的顺序表l中,删除所有值相等的多余元素。要求时间复杂度为o(n),空间复杂度为o(1)。
时间: 2023-04-30 14:01:13 浏览: 145
设计算法实现删除顺序表中多余重复元素.txt
\u53ef\u4ee5\u901a\u8fc7\u4ee5\u4e0b\u7b97\u6cd5\u6765\u5220\u9664\u8868l\u4e2d\u6240\u6709\u503c\u76f8\u7b49\u7684\u591a\u4f59\u5143\u7d20:
1. \u521b\u5efa\u4e00\u4e2a\u65b0\u7684\u8868m\uff0c\u5e76\u5c06l\u4e2d\u7684\u5143\u7d20\u4ee5\u4e0b\u9762\u7684\u6cd5\u5f8b\u8f6c\u5165\u5230m\u4e2d:
```python
m = []
for i in l:
if i not in m:
m.append(i)
```
2. \u901a\u8fc7set() \u51fd\u6570\u53d6\u5f97\u8868l\u4e2d\u7684\u552f\u4e00\u503c:
```python
m = list(set(l))
```
\u8981\u6c42\u65f6\u95f4\u590d\u6742\u5ea6\u4e3ao(n)\uff0c\u7a7a\u95f4\u590d\u6742\u5ea6\u4e3ao(1)\uff0c\u53ef\u4ee5\u901a\u8fc7\u4e0b\u9762\u7684\u65b9\u6cd5\u6765\u8ba1\u7b97:
```python
# \u8ba1\u7b97\u65f6\u95f4\u590d\u6742\u5ea6o(n)
import time
start_time = time.time()
# \u4ee5\u4e0a\u4e24\u4e2a\u65b9\u6cd5\u4e2d\u4efb\u9009\u4e00\u4e2a\u8fdb\u884c\u5220\u9664\u91cd\u590d\u5143\u7d20
# ...
end_time = time.time()
time_taken = end_time - start_time
print("o(n) \u65f6\u95f4\u590d\u6742\u5ea6\uff1a", time_taken)
# \u8ba1\u7b97\u7a7a\u95f4\u590d\u6742\u5ea6o(1)
import sys
# \u8ba1\u7b97\u65b0\u521b\u5efa\u8868m\u7684\u8d85\u7f51\u5185\u5b58\u5927\u5c0f
m_size = sys.getsizeof(m)
# \u8ba1\u7b97\u65b0\u521b\u5efa\u7684\u7a7a\u95f4\u7684\u8d85\u7f51\u5185\u5b58\u5927\u5c0f
empty_size = sys.getsizeof([])
# \u8ba1\u7b97\u7a7a\u95f4\u590d\u6742\u5ea6
o_1 = m_size / empty_size
print("o(1) \u7a7a\u95f4\u590d\u6745\u5ea6\\uff1a", o_1)\n```
阅读全文