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

来源:互联网 发布:mac 搜狗不能使用 编辑:程序博客网 时间:2024/06/07 09:12

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;}

0 0
原创粉丝点击