Leetcode-Remove Duplicates from Sorted Array-Python

来源:互联网 发布:cf提示网络出现异常 编辑:程序博客网 时间:2024/06/04 01:23

Remove Duplicates from Sorted Array

给定一个排序数组,将数组中的重复元素去除,并返回修改后的数组长度。
Description
解题思路
题目要求不能分配额外空间,由于python中列表是传引用,因此可以对传入的列表进行原地修改。由于数组已经排序,因此可以通过新建一个下标两两比较删除重复的元素。
注意
题目中 It doesn’t matter what you leave beyond the new length,因此超出长度部分的重复元素不需要考虑。

def removeDuplicates(self, nums):        """        :type nums: List[int]        :rtype: int        """        if not nums:            return 0        newIndex = 0        for i in range(1, len(nums)):            if nums[i] != nums[newIndex]:                        newIndex += 1                nums[newIndex] = nums[i]        return newIndex+1
阅读全文
0 0
原创粉丝点击