您的位置:首页 > 其它

Remove Duplicates from Sorted Array

2015-07-02 15:54 351 查看
描述

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].

中文:

给一个排序的数组,移除掉重复的元素,让每个元素只出现一次,然后返回新的长度。

注意必要分配给数组额外的空间,必须存放在固定的内存

分析:定义i,j表示数组的位置。

如果j指向的数组与i指向的数据重复,则j移动到下一个位置。

如果指向的值不重复,则将i+1,数据移动到i+1,j继续增加。

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n=nums.size();
int i,j,k;
if(n==0)
return 0;
i=0;j=1;
for(k=1;k<n;++k)
{
if(nums[i]!=nums[j])
{
i++;
nums[i]=nums[j];
j++;
}
else
j++;
}
return i+1;
}
};


Runtime: 32 ms

注意

1.首先要判断这个数组是否为空,如果为空的话,情况特殊。

注意对边界情况要考虑清楚。

2.另外多定义了一个数据k,多占用了一个空间,可以省略这个k,用j当做循环就可以了。可以做一些改进。

c语言版本

int removeDuplicates(int* nums, int numsSize) {
if(numsSize==0)
return 0;
int i,j;
i=0;
for(j=1;j<numsSize;++j)
{if(nums[i]!=nums[j])
nums[++i]=nums[j];
}
return i+1;
}


Runtime: 16 ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: