LeetCode

来源:互联网 发布:信盈达 知乎 编辑:程序博客网 时间:2024/05/16 18:52

Q:
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.

A:

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

注释:
从列表的第二个数(index=1)处开始遍历,与pre(初始为0)位置上的数进行比较,若相等,不做处理,继续;若不相等,则pre进一,将pre位置上的值更新;继续循环。
最后返回pre+1,即最终无重复数字列表的个数

原创粉丝点击