80. Remove Duplicates from Sorted Array II

来源:互联网 发布:网络编程培训 百度云 编辑:程序博客网 时间:2024/05/22 08:07

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

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

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

Subscribe to see which companies asked this question.

先翻译题目:这道题其实是题26的另一个版本,要求对给定的排序好的数组进行操作,将其中重复超过两次的数字移除,然后返回新数组的长度;

这里相比第26题多加了一个记录重复次数的计数器k,初始化k=0;比较游标i和游标j指向的元素,若重复则k++,否则k归零;

若是游标i与游标j指向的元素相同,则k++,然后查看k的值是否大于或者等于2;若是,则继续j对数组的遍历;

若不是,即k=1,重复了一次,i++,将j指向的数组元素的值赋值给i指向的数组元素;

若是游标i与游标j指向的元素不同,则k归零,然后i++,将j指向的数组元素的值赋值给i指向的数组元素;

最后遍历结束,将i加一,则得到数组的长度;

做该题时发生一个错误是nums.size()的这个括号总是忘了写;

记住别遗漏对空数组的初始判断;


以下为代码示例:

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


};

0 0
原创粉丝点击