Given a sorted array, you need to delete the repeating elements in place so that each element appears only once, returning the new length of the array after removal.
Instead of using extra array space, you must modify the input array in place and complete it with O (1) Extra space.
Example 1:
Nums 1
2
. You do not need to consider elements that are beyond the new length in the array.
Example 2:
Given 0
1
2
3
4
. You do not need to consider elements that are beyond the new length in the array.
Description
Why is the return value an integer, but the answer to the output is an array?
Note that the input array is passed in a "reference" manner, which means that modifying the input array in the function is visible to the caller.
You can imagine the internal operation as follows:
The nums is passed in a "reference" manner. That is, do not make any copy of the argument int len = removeduplicates (nums);//Modifying an input array in a function is visible to the caller. Depending on the length returned by your function, it prints all the elements within that length range in the array. for (int i = 0; i < len; i++) {print (nums[i]);}
Idea: Use quick and slow pointer, fast pointer traversal, slow pointer record number of non-repeating elements, each encounter new elements according to the slow pointer to the corresponding position. Code:
Class Solution: def removeduplicates (self, Nums): "" " : Type Nums:list[int] : Rtype:int " "" If not nums: return 0 k = 0 for i in range (1, Len (nums)): if nums[k]! = Nums[i]: k + = 1 nums[k] = Nums[i] return k + 1if __name__ = = ' __main__ ': s = solution () s.removeduplicates ([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])
Leetcode-26. Delete duplicates in a sorted array