您的位置:首页 > 其它

Remove Duplicates from Sorted Array II

2015-07-02 16:34 295 查看
描述

Follow up for ”Remove Duplicates”: What if duplicates are allowed at most twice?

For example, Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3]

中文

让排好序的数组最多重复两次。

分析:和上题一样,只要间距相差2就可以了。

不过还是要注意一些。

k表示循环

i表示新排列的数组下标

j表示旧排列的数组下标

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

}
};


Runtime: 20 ms

c语言版本

int removeDuplicates(int* nums, int numsSize) {

if(numsSize==0)

return 0;

if(numsSize<2)

return numsSize;

int i,j,k;

i=1;j=2;

for(k=2;k<numsSize;++k)

{

if(nums[i-1]!=nums[j])

{

++i;

nums[i]=nums[j];

++j;

}

else

++j;

}

return i+1;

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