题目描述
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:
因为所给数组已经是有序的,所以我们只需遍历一遍,遇到重复的跳过,遇到和前值不相等的,将其覆盖到前值的后一个位置。
思路2:
对于更为普遍的情况,如果数组是无序的,经过去重后数组仍按初始顺序排列,那么采用如下方法:
- 使用HashMap<Integer,Integer>来保存键值对<值,个数>,int类型的变量记录去重后数组的长度;
- 使用Queue<Integer>来记录重复数字的位置,将后续未重复的数填充到相应位置;
代码
思路1:
public static int removeDuplicates(int[] A) {
int length = 1;
if(A==null || A.length==0)
return 0;
if(A.length==1)
return 1;
int lastPos = 0;
for(int i = 1;i < A.length;i++){
while(i < A.length && A[i] == A[lastPos]){
i++;
}
if(i < A.length){
A[lastPos+1] = A[i];
lastPos += 1;
length++;
}
}
return length;
}
思路2:
public static int removeDuplicates(int[] A) {
int length = 0;
if(A==null || A.length==0)
return 0;
if(A.length==1)
return 1;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
Queue<Integer> posQueue = new ArrayDeque<Integer>();
for(int i = 0;i < A.length;i++){
if(!map.containsKey(A[i])){
length++;
map.put(A[i], 1);
if(!posQueue.isEmpty()){
A[posQueue.poll()] = A[i];
posQueue.offer(i);
}
} else {
posQueue.offer(i);
}
}
return length;
}