LeetCode | Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

 Total Accepted: 61826 Total Submissions: 196575My Submissions

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.

Show Tags














做法:set存不重复的值,清空原来的vector,再把set对象copy进vector对象里去,主要是copy。

代码:

class Solution {
public:
    int removeDuplicates(vector<int>& nums){
       set<int> temp(nums.begin(),nums.end());
       nums.clear();
       nums.resize(temp.size());
       std::copy(temp.begin(), temp.end(), nums.begin());
       return temp.size();
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/Tobyuyu/p/4965328.html