leetcode_c++:Remove Duplicates from Sorted Array(026)

  • 题目

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.

  • STL
  • 复杂度:O(n)
#include<iostream>
#include<algorithm>
#include<vector>


using namespace std;
const int N = 0;

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

int main() {

    return 0;
}
  • 双指针
    复杂度:O(N)
#include<iostream>
#include<algorithm>
#include<vector>


using namespace std;
const int N = 0;

class Solution {
public:
    int removeDuplicates(vector<int> &nums) {
        int n=nums.size();
        if(!n) return NULL;
        int num=1;
        for(int i=1;i<nums.size();++i)
            if(nums[i]!=nums[i-1])
                nums[num++]=nums[i];  //num和i是双指针
        return num;

    }
};
int main() {

    return 0;
}
  • map
    O(nlgn)
这里写代码片

你可能感兴趣的:(leetcode_c++:Remove Duplicates from Sorted Array(026))