LeetCode26 Remove Duplicates from Sorted Array(Python字典妙用)

来源:互联网 发布:C语言实现循环链表 编辑:程序博客网 时间:2024/06/03 15:14

LeetCode的第26题是非常简单的一道题目,大意就是给定一个排序好的数组,但是该数组中存在重复元素,要求操作该数组,去掉其中的重复元素,同时统计去重之后数组的长度。原题的做法是使用两个指针,比较对应元素,同时修改数组,附上O(n)Python代码:

class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        index = 0        length = len(nums)        if length < 2:            return length        for i in range(1,length):            if nums[index] != nums[i]:                index += 1                nums[index] = nums[i]        index += 1        return index

但是,解决了这个题目之后,我们还可以思考另一个问题,本题麻烦的地方在于要求修改原数组,但方便的地方是给定的数组是排序过的,那现在我们修改一下原题的条件,首先不需要修改原数组,但是数组元素变成无序的,这时候如何解决呢?使用Python里的字典同样可以实现O(n)的效率。代码附上:

class Solution(object):    def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        result = 0        cnt = {}        for i in range(len(nums)):            if nums[i] not in cnt:                cnt[nums[i]] = i        return len(cnt)
遍历一遍数组,只要不在字典中的就把该元素添加进去,但是对于重复元素,由于字典中已经存在,则不会添加,最后得到的字典的长度就是不重复的元素的个数

0 0
原创粉丝点击