26. Remove Duplicates from Sorted Array and 80. Remove Duplicates from Sorted Array II

来源:互联网 发布:保健品网络推广策划 编辑:程序博客网 时间:2024/05/17 18:19

第一题、26. Remove Duplicates from Sorted 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.
方法一、直接暴力法

int removeDuplicates(vector<int>& nums) {        if(nums.size()<=1)        {            return nums.size();        }        vector<int> :: iterator it ;        vector<int> :: iterator it1;        for(it= nums.begin(),it1 = nums.begin()+1;it1!=nums.end();)         {            if(*it == *it1)            {                it1 = nums.erase(it1);            }               else            {                it++;                it1++;            }        }        return nums.size();    }

方法二、计数法

int removeDuplicates(vector<int>& nums) {        int count = 0;        for(int i = 1; i < n; i++){            if(A[i] == A[i-1]) count++;            else A[i-count] = A[i];        }        return n-count;    }

第二题、80. 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 1, 1, 2, 2 and 3. It doesn’t matter what you leave beyond the new length

int removeDuplicates(vector<int>& nums) {        int n = nums.size(), count = 0;        for (int i = 2; i < n; i++)            if (nums[i] == nums[i - 2 - count]) //注意该句的if判断条件是if(nums[i] == nums[i - 2 - count]),由于如果不满足该条件时,数组中的元素是会往前移动的,所以要i-2-count                count++;            else nums[i - count] = nums[i];        return n - count;    }
0 0
原创粉丝点击