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 should return length = 2
, and A is now [1,2]
.
1 int removeDuplicates(int A[], int n) 2 { 3 int fast = 0, slow = 0; 4 while (fast < n) 5 { 6 if (fast == 0 || A[fast] != A[fast-1]) 7 { 8 A[slow] = A[fast]; 9 slow++; 10 } 11 fast++; 12 } 13 14 return slow; 15 }
时间: 2024-10-06 14:08:48