1. 程式人生 > >刪除有序陣列中的重複元素 Remove Duplicates from Sorted Array

刪除有序陣列中的重複元素 Remove Duplicates from Sorted Array

題目源自於Leetcode。

題目: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].

思路:左/右兩個指標控制著原地的新/舊陣列。

注意時刻關注著右指標是否到達末尾

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        if(n<=1)
            return n;
        int left, right;
        left = 0;
        right = 1;
        while(right<n)
        {
            while(right<n && A[right] == A[left])
                right++;
            if(right == n)
                break;

            left++;
            A[left] = A[right];
            right++;
        }
        return left+1;
    }
};

或者用for迴圈也一樣。

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


如果想偷懶使用STL演算法的話,可以先unique()將重複元素仍在後面,然後再返回非重複元素的個數。但是這樣的實現效率並沒有直接雙指標快。

class Solution {
public:
    int removeDuplicates(int A[], int n) {
        return distance(A, unique(A, A+n));
    }
};