Tuesday, September 24, 2013

Remove Duplicates from Sorted Array

Problem:
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 A = [1,1,2],
Your function should return length = 2, and A is now [1,2].
Solution:
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int iter = 0;
        if (n == 0)
            return 0;
        for (int i = 0; i < n - 1; i++) {
            if (A[i] != A[i+1])
                A[iter++] = A[i];
        }
        A[iter++] = A[n - 1];
        return iter;
    }
};

==== Second time ====
class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int result = 0;
        if (n == 0)
            return result;
        for (int i = 0; i < n; i++) {
            if (A[i] != A[result]) {
                result++;
                A[result] = A[i];
            }
        }
        return result + 1;
    }
};

==== Third time =======

int removeDuplicates(vector<int>& nums) {
        int ans = 1, iter = 0;
        if (nums.size() == 0) {
            return 0;
        }
        
        int num_comp = nums[iter];
        for (iter = 1; iter < nums.size(); iter++) {
            if (nums[iter] != num_comp) {
                nums[ans++] = nums[iter];
                num_comp = nums[iter];
            }
        }
        
        return ans;
    }
=============
class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int cur = 1;
        int prev = 0;
        if (nums.size() == 0) {
            return prev;
        }
        int prev_num = nums[0];
        prev = 1;
        while (cur < nums.size()) {
            if (nums[cur] != prev_num) {
                nums[prev++] = nums[cur]; 
            }
            prev_num = nums[cur];
            cur++;
        }
        return prev;
    }
};

No comments:

Post a Comment