The title

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

Instead of using extra array space, you must modify the input array in place and do so with O(1) extra space.

Example 1: Given the 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 changed to 1,2. You don't need to worry about the element after the new length in the array. 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 nums array are modified to 0,1, 2,3, 4. You don't need to worry about the element after the new length in the array.Copy the code

Description:

Why is the return value an integer, but the output answer is an array?

Note that the input array is passed “by reference,” which means that modifying the input array in a function is visible to the caller.

You can imagine the internal operation as follows:

// Nums is passed by reference. That is, it does not make any copies of the arguments int len = removeDuplicates(nums);

// Modifying the input array in a function is visible to the caller. // Depending on the length returned by your function, it prints out all elements in the array within that length. for (int i = 0; i < len; i++) { print(nums[i]); }

Their thinking

class Solution:
    def removeDuplicates(self, nums:[int]) -> int:
        lenDup = len(set(nums))# Length after weight removal
        if len(nums) == 1: return 1
        i = 0
        while i < lenDup-1:
            print(nums[i])
            if nums[i] == nums[i+1]:
                temp = nums[i]
                print(nums[i+1:])
                # nums[i:-1] = nums[i+1:]
                nums[i+1: len(nums)-1] = nums[i+2:]
                nums[-1] = temp
            else:
                i += 1
        nums = nums[:lenDup]
        return len(nums)
Copy the code