Remove Duplicates from Sorted Array--LeetCode

来源:互联网 发布:淘宝怎么寄到美国 编辑:程序博客网 时间:2024/06/05 17:10

1.题目

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.

2.题意

不开辟额外空间,对有序数组去重

3.分析

1)数组已经有序,所以重复元素一定相邻
在[1, nums.size())范围内遍历数组
若一个数不等于它的前一个数,则将该数放回原数组
时间复杂度O(n),空间复杂度O(1)
2)~ 3)借助STL也可以AC
4)在[1, len)范围内遍历数组
将nums[i]与nums[index - 1]作比较
若不相等,则将nums[i]放回原数组,达到去重的目的
这种解法可以拓展应用于这一类问题
如Remove Duplicates from Sorted Array II

4.代码

1)

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size() == 0)            return 0;        int index = 1;        for(int i = 1; i < nums.size(); ++i)        {            if(nums[i] != nums[i - 1])            {                nums[index] = nums[i];                ++index;            }        }        return index;    }};

2)

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size() == 0)            return 0;        return distance(nums.begin(), unique(nums.begin(), nums.end()));    }};

3)

class Solution {public:    int removeDuplicates(vector<int>& nums) {        if(nums.size() == 0)            return 0;        return distance(nums.begin(), removeDuplicates(nums.begin(), nums.end(), nums.begin()));    }    template<typename InIt, typename OutIt>    OutIt removeDuplicates(InIt first, InIt last, OutIt output)    {        while(first != last)        {            *output++ = *first;            first = upper_bound(first, last, *first);        }        return output;    }    };

4)

class Solution {public:    int removeDuplicates(vector<int>& nums) {        int len = nums.size();        if(len <= 1)            return len;        int index = 1;        for(int i = 1; i < len; ++i)        {            if(nums[i] != nums[index - 1])            {                nums[index] = nums[i];                ++index;            }        }        return index;    }};
阅读全文
0 0
原创粉丝点击