溫馨提示×

溫馨提示×

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

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

[LeetCode]26. Remove Duplicates from Sorted Array

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

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.


題意:

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


思路:

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

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

3)*(nums + nLen) = *(nums + cnt + 1)語句說明:如果沒出現重復元素,那么nLen == cnt + 1;如果出現重復元素,那么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問一下細節

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

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女