26、80 Remove Duplicates from Sorted Array(重复1次或2次)--Array

来源:互联网 发布:最终幻想猫女捏脸数据 编辑:程序博客网 时间:2024/05/01 20:35

注意:因为已排序,故重复的元素肯定是相邻的,如111223

26.Remove Duplicates from Sorted Array I(重复1次)--Array

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.

Subscribe to see which companies asked this question

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int newIndex = 0;        int sz = nums.size();        if(sz <= 1)                     // sz==0是空数组、sz==1是访问nums[oldIndex]从nums[1]开始会越界            return sz;        for(int oldIndex = 1; oldIndex != sz; ++oldIndex)        {            if(nums[newIndex] != nums[oldIndex])                nums[++newIndex] = nums[oldIndex];        }        return (++newIndex);    }};



80.Remove Duplicates from Sorted Array II(重复2次)--Array

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


class Solution1 {public:    int removeDuplicates(vector<int>& nums)     {        int newIndex = 0;        int sz = nums.size();        int duplicatedTimes = 0;    // 已重复的次数                if(sz <= 1)            return sz;                    for(int oldIndex = 1; oldIndex != sz; ++oldIndex)        {            if(nums[newIndex] == nums[oldIndex])    // 相等的话,只有重复次数<2才会放入结果数组            {                ++duplicatedTimes;                  //  ++重复次数                if(duplicatedTimes < 2)             //  重复次数<2,则放入结果数组                    nums[++newIndex] = nums[oldIndex];            }            else                                    // 不相等的话,都会放入结果数组            {                nums[++newIndex] = nums[oldIndex];                duplicatedTimes = 0;                // 重复次数清0            }         }        return ++newIndex;    }};



                                             
0 0
原创粉丝点击