0
点赞
收藏
分享

微信扫一扫

删除数组中的重复项

技术只适用于干活 2022-04-05 阅读 72
python算法

题目描述

给定一个数组,你需要删除其中重复出现的元素,只保留最后一次出现的重复元素,使得每个元素只出现一次,返回新数组,并保证新数组中的元素顺序与原数组一致。

示例

示例一
Input: [2, 3, 6, 3, 5, 6, 7]
Output: [2, 3, 5, 6, 7]

示例二:
Input: [5, 9, 6, 2, 4, 6]
Output: [5, 9, 2, 4, 6]

方法一

暴力法:创建一个空数组a,直接从后向前依次判断当前数是否在数组a中,若不在则加入数组a。

class Solution:
    def removeDuplicate(self, array):
        b = []
        for i in array[::-1]:
            if not i in b:
                b = [i] + b
        return b

方法二

字典法:创建字典a,依次遍历数组array,对于数组中的每个数,字典a只保留了其最后一次出现的位置下标,然后对字典中的每一项按字典值的大小进行排序。则此时排完序的字典的键即为所求数组。

    def removeDuplicate3(self, array):
        dic = dict()
        for i, item in enumerate(array):
            dic[item]=i
        a = sorted(dic.items(), key=lambda x: x[-1])
        b = []
        for x, _ in a:
            b.append(x)
        return b

方法三

字典法:按数组中值出现的先后顺序创建一个包含每个值位置的字典m,然后依次遍历数组进行判断。若当前数对应的值的长度为1,则加入数组中,不为1,则判断是否等于保存的最后一个位置的下标,等于则加入数组中。

class Solution:
    def removeDuplicate(self , array ):
        # write code here
        m = defaultdict(lambda: [])
        for i in range(len(array)):
            m[array[i]].append(i)
        res = []
        for i, num in enumerate(array):
            if len(m[num]) == 1:
                res.append(num)
            else:
                if i == m[num][-1]:
                    res.append(num)
        return res
举报

相关推荐

0 条评论