数组去重Python 几种解法

版权声明:本文为博主原创文章,未经博主允许不得转载。 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

类似题目的解法:
https://github.com/CyC2018/CS-Notes/blob/master/notes/%E5%89%91%E6%8C%87%20offer%20%E9%A2%98%E8%A7%A3.md#3-%E6%95%B0%E7%BB%84%E4%B8%AD%E9%87%8D%E5%A4%8D%E7%9A%84%E6%95%B0%E5%AD%97

猜你喜欢

转载自blog.csdn.net/gsch_12/article/details/82015841
今日推荐