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 nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
题意: 给一个按从小到大排序好的数组,让你去掉其中重复出现的数字,使得返回的数组是都只由出现一次的数字组成.并返回新数组的长度.
范例如上所示.
思路: 这道题很简单,只要设定两个指针,一个指向新数组的最后一个元素,另一个按原数组从头到尾遍历一次,若发现元素值与新数组最后一个元素不一样,则将这个元素添加到新数组后边.
int removeDuplicates(int* nums, int numsSize) {
int *pFront, *pNext;
int length;
int size;
if( 0 == numsSize)
return 0;
pFront = //新数组最后一个元素
pNext = nums; //遍历原数组
size = 0;
length = 1;
while(size != numsSize)
{
if(*pNext != *pFront)
{
++pFront;
*pFront = *pNext;
++length;
}
++size;
++pNext;
}
return length;
}