LeetCode专题-Python实现之第26题:Remove Duplicates from Sorted Array

导航页-LeetCode专题-Python实现

相关代码已经上传到github:https://github.com/exploitht/leetcode-python
文中代码为了不动官网提供的初始几行代码内容,有一些不规范的地方,比如函数名大小写问题等等;更合理的代码实现参考我的github repo

1、读题

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

一个有序数字,要求去掉重复的元素然后返回新的长度,不要申请额外空间。
举个例子,给定数组:[1,1,2],程序需要处理成[1,2,…]然后返回2,也就是前2个元素是去重之后得到的结果,超过2的部分是什么无所谓,是1也行是2也行。

2、解题

这类题想明白了其实解题很简单,重复的需要去掉,无非就是遍历数组,发现重复,就把后面的往前移,把重复值覆盖掉。具体说,可以维护2个指针,慢指针开始指向数组第一个元素,快指针指向第二个元素,然后快指针不断判断自己当前元素和前一个元素是否相同,相同则快指针后移,不相同则将当前值赋值给慢指针的后一个元素,慢指针后移。最后慢指针指向的元素及前面所有元素都是不重复的。具体过程参考如下代码和注释:

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        # 删除列表中的重复项,返回操作后的长度
        # [1,1,1,2,3,4,4,4,5] -> [1,2,3,4,5] 5
        # 维护2个索引,慢的s,快的f;s指向第一个元素,f的指向第二个元素;
        # 判断f和f前一个元素是否相等,相等则f后移;不等则s后移一个,值给s,然后f也后移
        if len(nums) <= 1:
            return len(nums)

        s = 0

        for f in range(1, len(nums)):
            if nums[s] != nums[f]:
                s += 1
                nums[s] = nums[f]
        return s + 1
posted @ 2017-10-12 17:44  胡说云原生  阅读(1293)  评论(0编辑  收藏  举报