[leetCode]26. Remove Duplicates from Sorted Array

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 nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

題意: 給一個按從小到大排序好的數組,讓你去掉其中重複出現的數字,使得返回的數組是都只由出現一次的數字組成.並返回新數組的長度.
範例如上所示.

思路: 這道題很簡單,只要設定兩個指針,一個指向新數組的最後一個元素,另一個按原數組從頭到尾遍歷一次,若發現元素值與新數組最後一個元素不一樣,則將這個元素添加到新數組後邊.

int removeDuplicates(int* nums, int numsSize) {
    int *pFront, *pNext;
    int  length;
    int  size;

    if( 0 == numsSize)
        return 0;

    pFront =   //新數組最後一個元素
    pNext  = nums;  //遍歷原數組
    size   = 0;
    length = 1;

    while(size != numsSize)
    {
        if(*pNext != *pFront)
        {
            ++pFront;
            *pFront = *pNext;

            ++length;
        }

        ++size;
        ++pNext;
    }

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