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]
.
解法:O(n)遍历数组,固定住一个值,将该值放入新数组中,同时遍历index往前推
public class Solution {
public int removeDuplicates(int[] A) {
if(A == null || A.length == 0) return 0;
int len = A.length;
int k = 0;
int i=0;
while(i<len){
int t = A[i];
A[k++] = t;
while(++i<len && A[i] == t);
}
return k;
}
}