LeetCode 之 Remove Duplicates from Sorted Array I II — C 实现

Remove Duplicates from Sorted Array

 I 

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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.

给定一个有序的数组,删除所有重复的元素使其在数组中只出现一次,返回新数组长度。

在原数组上操作,不能额外分配数组空间。

例如,给定一个输入数组 nums [1,1,2], 函数要返回长度为2,新数组为 [1,2].

分析:

使用两个索引分别标记已经唯一的元素的位置和还没有比较的位置,然后使用数组后面唯一的值覆盖重复的值。

int removeDuplicates(int* nums, int numsSize) {
    int posPre = 0; //指向已唯一的数组位置
    int index = 0;
    
    if(!nums || numsSize == 0)//空指针,或空数组
    {
        return 0;
    }
    
    ++index;
    while(index < numsSize)
    {
        if(nums[index] == nums[posPre]) //相等,只需向后查找
        {
            ++index;
        }
        else //不等,将元素紧接的放在已唯一的数组后,并继续向后查找
        {
            nums[++posPre] = nums[index++];
        }
    }
    
    return posPre+1;
}

Remove Duplicates from Sorted Array II

 

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.

允许一个数重复两次。

分析:

同 I 一样,也需要两个分别指向已经处理和还未处理的位置,设置一个标志表示已经出现过一次,再次出现时将已处理索引后移,如果还有相同值则用数组后面的数填充,没有将标志清0。

int removeDuplicates(int* nums, int numsSize) {
    int posPre = 0;
    int twoFlag = 0;
    int index = 0;
    
    if(!nums || numsSize == 0)//空指针或空数组
    {
        return 0;
    }
    
    ++index;
    while(index < numsSize)
    {
        if(nums[index] == nums[posPre])//相等
        {
            if(twoFlag)//已有两个相等元素,继续向后查找
            {
                ++index;
            }
            else//只有一个相等,放入指定位置
            {
                nums[++posPre] = nums[index++];
                twoFlag = 1;
            }
        }
        else
        {
            nums[++posPre] = nums[index++];
            twoFlag = 0;
        }
    }
    
    return posPre+1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值