Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

 Total Accepted: 22879 Total Submissions: 70824My 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 A = [1,1,2],

Your function should return length = 2, and A is now [1,2]

這題與Remove Duplicates from Sorted List類似,只不過換成了數組,要把排好序的數組的元素變爲不重複,且要求原地操作。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int new_arr_cur, arr_cur;
        new_arr_cur = arr_cur = 0;
        
        while (arr_cur < n) {
            A[new_arr_cur++] = A[arr_cur]; // assign
            //skip duplicates
            while (arr_cur < n && A[arr_cur] == A[new_arr_cur - 1]) {
                arr_cur++;
            }
        }
        
        return new_arr_cur;
    }
};

Remove Duplicates from Sorted Array II

 Total Accepted: 17014 Total Submissions: 55726My Submissions

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

這裏是最多允許兩次重複,要在上面的代碼進行修改。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        int new_arr_cur, arr_cur, count;
        new_arr_cur = arr_cur = 0;
        const int DUPLICATE_NUM = 2;
        while (arr_cur < n) {
            A[new_arr_cur++] = A[arr_cur++];
            count = 1;
            //add allowed duplicates
            while (count < DUPLICATE_NUM && arr_cur < n && A[arr_cur] == A[new_arr_cur - 1]) {
                A[new_arr_cur++] = A[arr_cur++];
                count++;
            }
            //skip leftmost duplicate
            while (arr_cur < n && A[arr_cur] == A[new_arr_cur - 1]) {
                arr_cur++;
            }
        }
        return new_arr_cur;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章