Remove Duplicates from Sorted Array II

来源:互联网 发布:ubuntu caffe python 编辑:程序博客网 时间:2024/06/07 12:53

描述
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

0 0
原创粉丝点击