leetcode26 remove duplicates in sorted array

Given a sorted array, you need to remove duplicate elements in place so that each element occurs only once, and return the new length of the removed array.

Don't use extra array space, you have to modify the input array in- place and do it with O(1) extra space.

Example 1:

Given an array nums = [1,1,2] ,

The function should return a new length of 2 , and the first two elements of the original array nums are modified to 1, 2.

You don't need to consider elements in the array beyond the new length.

Example 2:

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

The function should return a new length of 5 , and the first five elements of the original array nums are modified to 0, 1, 2, 3, 4.

You don't need to consider elements in the array beyond the new length.

class Solution:
    def removeDuplicates(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length=len(nums)
        if length==0 or length==1:#The array is empty or has 1 length
            return len(nums)
        index=0
        for i in range(1,length):
            if nums[i]>nums[index]:
                index+=1
                nums[index]=nums[i]
        return index+1



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325800865&siteId=291194637