LeetCode, leetcodeoj
Link: Remove Duplicates from Sorted Array
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.
For example,
Given input array A = [1, 1, 2],
Your function shocould return length = 2, and A is now [1, 2].
The requirement for this question is to delete duplicate elements in an ordered array, so that each number appears only once, and return the new length of the array. Requirement: no additional space is allowed, that is, constant space complexity is required.
The idea of this question is to use two pointers: l and r. l records the positions of non-repeating elements. r traverses the array from the next of l. If the number at the r position is equal to the number at the l position, this number is repeated and not processed. If the number at the r position is not equal to the number at the l position, it indicates that the number is not repeated and must be placed in the next position of the l, and add l to 1.
Time Complexity: O (n)
Space complexity: O (1)
1 class Solution 2 { 3 public: 4 int removeDuplicates(int A[], int n) 5 { 6 if(n == 0) 7 return 0; 8 9 int l = 0;10 for(int r = 1; r < n; ++ r)11 if(A[r] != A[l])12 A[++ l] = A[r];13 return l + 1;14 }15 };
Reprinted please note the Source: LeetCode --- 26. Remove Duplicates from Sorted Array