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]
.
删除重复的数,并返回数组的长度
题目解析:
这道题目可以从快速排序算法得到启发:快排有两种,一种从左向右遍历,碰到比key大的,就将放到后面,再从后向前遍历;另一种是设两个下标指针,i和j,i指向当前遍历的数据里面都比key小的数据,i->j-1之间都是大于key的数据,j指向当前要判断的数据,如果arr[j]<=key,就将arr[i+1]和arr[j]交换。
但这个题目当中只是让删除数据,我们可以利用上述第二种方法,但不交换,直接arr[i+1] = arr[j]。不过具体实现的时候,和快排有一点点差别。
#include <stdio.h>
#include <stdlib.h>
int RemoveDuplicates(int arr[],int len);
int main()
{
int arr[10];
int n;
while(scanf("%d",&n) != EOF){
for(int i = 0;i < n;++i)
scanf("%d",&arr[i]);
int len = RemoveDuplicates(arr,n);
printf("len = %d\n",len);
for(int i = 0;i < len;++i)
printf("%d ",arr[i]);
printf("\n");
}
return 0;
}
int RemoveDuplicates(int arr[],int len)
{
int i,j;
if(arr == NULL || len <= 0)
return 0;
i = 0;
j = 1;
while(j < len){
if(arr[i] != arr[j] && ++i != j)
arr[i] = arr[j];
++j;
}
return i+1;
}