LeetCode---删除排序数组中的重复项II(C语言实现)

题目来源:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/description/

题目描述:

算法描述:

这题是在上篇博客的题目基础上,难度略微提升。详情见上篇博客:https://blog.csdn.net/qq_39241239/article/details/82560072

 相信你已经看过上篇博客的解题思路了,在此基础上。我们增加一个标志位count,用来标记重复次数。首先令count等于1,还是按照上篇博客的方法进行遍历数组,所不同的是,由于可以出现最多两个重复数字,所以当nums[i]==nums[length-1]&&count<2时,同样可以对length进行+1操作,并且把i为下标的数赋值给length为下标的位置。要特别注意的是,当nums[i]不等于nums[length-1],对数组进行操作时,不要忘记了把count重新赋值为1。

代码实现:

int removeDuplicates(int* nums, int numsSize) {
    if(numsSize==0||numsSize==1){
        return numsSize;
    }
    int length = 1;
    int count =1;
    for(int i=1;i<numsSize;i++){
        if(nums[i]==nums[length-1]&&count<2){
            nums[length++]=nums[i];
            count++;
        }else if(nums[i]!=nums[length-1]){
            nums[length++]=nums[i];
            count=1;
        }
    }
    return length;
}

猜你喜欢

转载自blog.csdn.net/qq_39241239/article/details/82560500