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 =
Given input array A =
[1,1,2]
,
Your function should return length =
Pointer problem, array in place operation. Use two pointer to indicate the end of non-duplicate array and where we have checked.
2
, and A is now [1,2]
.public int removeDuplicates(int[] A) { int n = A.length; if(n == 0 || n == 1) return n; int p1 = 0, p2 = 1; while(p2 < n) { while(p2 < n && A[p2] == A[p1]) p2++; if(p2 == n) break; p1++; A[p1] = A[p2]; p2++; } return p1+1; }
没有评论:
发表评论