【leetcode】26. Remove Duplicates from Sorted Array

一、题目描述(删除重复元素)

https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/

给定排序的数组nums,就地删除重复项,使每个元素只出现一次并返回新的长度。
不要为另一个数组分配额外的空间,必须通过使用O(1)额外内存修改输入数组来实现此目的。

Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

二、题目分析

删除重复元素,要求不能申请新的空间,哦原来要用两套下标呀,i和j,那就整吧

i为遍历下标,遍历整个数组,j为新数组下标,出现不同的数字,j增加1,不同的数字插入下标为j的数组中。(其实就是插在数组i前面部分,i已经遍历到后半截了,不会影响遍历的放心········)

三、代码实现

扫描二维码关注公众号,回复: 1919479 查看本文章
class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums)==0:
            return 0
        l=len(nums)
        j=1
        for i in range(1,len(nums)):
            if nums[i]==nums[i-1]:
                l=l-1
            else:
                nums[j]=nums[i]
                j=j+1
        return l
        

猜你喜欢

转载自blog.csdn.net/jinjinjin2014/article/details/80945404