从排序数组中删除重复项

参考:

https://blog.csdn.net/qitong111/article/details/79729639

https://blog.csdn.net/qq_25677349/article/details/80588952

题目:

https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/21/

给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

给定数组: nums = [1,1,2],

你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2
不需要理会新的数组长度后面的元素

 

我自己写的代码:

思路:

需要输出的是修改后的字符长度,可以考虑使用python中除去数组元素的函数,由于同样的数字可能出现2次以上,因此需要将 i++ 与 if 分开

注意:

python中不可以使用 i++ 而是 i=i+1

class Solution(object):
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        i=0
        while(i<len(nums)-1):
            if(nums[i]==nums[i+1]):
                nums.remove(nums[i])
            else:
                i=i+1
        return len(nums)
        

 

posted on 2019-03-27 11:50  雪原那么远  阅读(117)  评论(0编辑  收藏  举报

导航