Problem:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
Example
Given input array A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
Tags Expand
Related Problems Expand
My Solution:
In this question, a variable named ‘last’ is used to record the index of last element in the result array.
Go through the array, if the current element nums[i] is not equal to the last element of result array ‘nums[last]’,
add the current element to end of result array.
1 | /************************************************************************* |
Time complexity is O(n), space complexity is O(1)