版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gsch_12/article/details/82015841
整数数组里面有重复元素,如果不考虑数组顺序的改变就是可以排序,如何去重nlogn?如果要保留原有数组顺序,如何去重?
利用辅助空间,List,把元素重新加入,如果已加入的就不添加,这样只用遍历一次,留下不重复的元素O(n^2)
因为list自导的 x in list其实是O(n)的复杂度。
def unique(old_list):
newList = []
for x in old_list:
if x not in newList :
newList.append(x)
return newList
数组有重复,输出重复的元素
O(n^2)
def unique(old_list):
newList = []
for x in old_list:
if x not in newList :
newList.append(x)
for y in newList:
if y not in old_list:
print(y)
临时变量大法
声明临时变量tmp=data[0], index=0。变量data,如果相等则continue,不相等。将data[index]赋值为tmp,tmp=data[i], index++即可。
该解法空间复杂度为O(1), 时间复杂度为O(Nlogn),因为sorted()是个归并排序,
Timsort是一种混合的算法,它派生自归并排序和插入排序。它是2002年由Tim Peters为Python语言发明的。
Timsort的时间复杂度最好情况为O(n),平均情况为O(nlogn),最差情况为O(nlogn);空间复杂度为O(n)。
def uniqList04(data=None):
data = sorted(data)#这里就是O(nlogn)的复杂度了
tmp = data[0]
index = 0
for i, v in enumerate(data):
if tmp == v:
continue
else:
data[index] = tmp
tmp = v
index += 1
data[index] = tmp # 在foreach循环中,最后一次的tmp值没有赋给data
return data[:index+1] # 因为index从0开始,所以此处加1