LeetCode #26. Remove Duplicates from Sorted Array

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hh66__66hh/article/details/82595657

#26. Remove Duplicates from Sorted Array

##题目描述
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
Example 1:

Given 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 returned length.

Example 2:

Given nums = [0,0,1,1,1,2,2,3,3,4],

Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

It doesn't matter what values are set beyond the returned length.

##思路
该题给出一个数组,需要做的事情是将该数组中的数去重,返回去重后数组的元素个数,且经过该函数处理以后,传进来的数组必须已经去重了。处理的过程中主要使用到了vector和map,尤其是vector中erase的使用。

##代码

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        map<int,int>m;
        m.clear();
        int i, j, k, ans;
        ans = 0;
        for(i=0; i<nums.size(); i++) {
            if(m.count(nums[i])==0) {
                ans++;
                m[nums[i]] = 1;
            }
            else{
                nums.erase(nums.begin()+i);
                i--;
            }
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/hh66__66hh/article/details/82595657