RemoveDuplicate from sorted Array
/**
* RemoveDuplicate from sorted Array
* 题目:给定一个数组,删除数组中重复的元素,保证每个元素只出现一次,并返还数组的长度
* 例如: A[1,1,2]
* 返回: [1,2] 长度为2
*
* 思路:
* 1.遍历数组,用index出现了重复元素的个数
* 2.如果数组的前一个元素当前元素相等那么就表示出现了重复的元素,index++,
* 3.如果数组前一个元素当前元素不相等,就把当前的元素放到[i-index]的位置上
*/
public class RemoveDuplicatefromsortedArray {
public static int removeDupDuplicate(int[] A){
if(A.length==0){
return 0;
}
int index=0;
for(int i=1;i<A.length;i++){
if(A[i]==A[i-1]){
index++;
}else{
A[i-index]=A[i];
}
System.out.println(Arrays.toString(A));
}
return A.length-index;
}
public static void main(String[] args) {
int[] A={1,2,3,3,4,5};
int length=removeDupDuplicate(A);
System.out.println(length);
}
}