溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

[LeetCode]26. Remove Duplicates from Sorted Array

發(fā)布時間:2020-08-07 09:57:14 來源:網絡 閱讀:285 作者:風子余 欄目:編程語言

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.


題意:

根據(jù)給定的排序數(shù)組,刪除重復元素,并返回刪除重復元素后數(shù)組的長度。但是申請額外的空間。


思路:

1)如果數(shù)組長度為1或者為0,直接返回。

2)把數(shù)組的當前位置元素與后一位置元素進行對比,如果相等,無需做什么;如果不相同,那么把不重復數(shù)組標示nLen加一,并把第二個替換。

3)*(nums + nLen) = *(nums + cnt + 1)語句說明:如果沒出現(xiàn)重復元素,那么nLen == cnt + 1;如果出現(xiàn)重復元素,那么nLen就是重復元素位置,用不重復元素cnt + 1替換即可(比如1,2,2,3此時2,3第一個元素是重復元素,替換即可)

int removeDuplicates(int* nums, int numsSize)
{
    if ( numsSize == 1 || numsSize == 0 ) 
    {   
        return numsSize;
    }   
    /* 1 2 2 3 4*/
    int cnt  = 0;
    int nLen = 0;
    for ( cnt = 0; cnt < numsSize - 1; cnt += 1 ) 
    {   
        if ( *(nums + cnt) != *(nums + cnt + 1) )
        {   
            nLen += 1;
            *( nums + nLen ) = *(nums + cnt + 1); 
        }   
    }   
    return nLen + 1;
}


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI