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]
.
解题思路:
用一个变量来统计在i位置以前总共有多少个duplicate,然后将此元素向前移动几步
Java Code:
public int removeDuplicates(int[] A) { int moveStep = 0; for(int i = 1; i < A.length; i++){ if(A[i] == A[i-1]){ moveStep++; } A[i-moveStep] = A[i]; } return A.length - moveStep; }
No comments:
Post a Comment