[LeetCode] Remove Duplicates from Sorted Array [19]

題目

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(A==NULL || n<=0) return 0;
        int start = 1;
        int back = A[0];
        for(int i=1;i<n;++i){
            if(A[i] != back){
                A[start++] = A[i];
                back = A[i];
            }
        }
        return start;
    }
};

如果你覺得本篇對你有收穫,請幫頂。
另外,我開通了微信公衆號--分享技術之美,我會不定期的分享一些我學習的東西.
你可以搜索公衆號:swalge 或者掃描下方二維碼關注我

(轉載文章請註明出處: http://blog.csdn.net/swagle/article/details/29211429 )

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