1. 程式人生 > >LeetCode - Remove Duplicate Numbers In Array

LeetCode - Remove Duplicate Numbers In Array

解法一 O(n) hashtable

class Solution {
public:
    int deduplication(vector<int> &nums) {
        unordered_set<int> temp;
        int n = nums.size();
        int idx = n-1, i=0;
        for(;i<=idx;i++){
            int cur = nums[i];
            if(temp.find(nums[i])!=temp.end()){
                swap(nums[i--], nums[idx--]);
            }else temp.insert(cur);
        }
        return temp.size();
    }
};

解法二 O(nlogn) sort & two pointers

class Solution {
public:
    int deduplication(vector<int> &nums) {
        if(nums.empty()) return 0;
        sort(nums.begin(), nums.end());
        int n=nums.size(), index=0;
        for(int i=1;i<n;i++){
            if(nums[i]!=nums[i-1]) 
                nums[++index]=nums[i];
        }
        return index+1;
    }
};