1. 程式人生 > >26. Remove Duplicates from Sorted Array的C++解法(unique去重)

26. Remove Duplicates from Sorted Array的C++解法(unique去重)

題目描述:https://leetcode.com/problems/remove-duplicates-from-sorted-array/

無腦演算法:

class Solution {
public:
    int removeDuplicates(vector<int> &nums) {
        if (nums.size()==0||nums.size()==1) return nums.size();
        int i=1;
        while (i<nums.size())
            if (nums[i]==nums[i-1]) nums.erase(nums.begin()+i);
            else i++;
       return nums.size();
    }
};

使用unique函式更快:

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