溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Leetcode 26. Remove Duplicates from Sorted Array C語(yǔ)言

發(fā)布時(shí)間:2020-09-02 15:54:33 來(lái)源:網(wǎng)絡(luò) 閱讀:747 作者:努力的C 欄目:編程語(yǔ)言
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.

題意:從排好序的數(shù)組里刪掉重復(fù)元素,返回新的數(shù)組長(zhǎng)度。不能額外申請(qǐng)空間。

int removeDuplicates(int* nums, int numsSize) {
    // int cand=nums[0];
    // for(int i=1;i<numsSize;i++){
    //     if(cand==nums[i]){
    //         numsSize--;
    //     }else{
    //         cand=nums[i];
    //     }
    // }
    int index=0;
    int j;
    for(j=1;j<numsSize;j++){
        if(nums[index]!=nums[j]){
            nums[++index]=nums[j];
        }
    }
    return index+1;

}

PS:咦。。。又是一個(gè)雙指針問(wèn)題。用兩個(gè)指針index和j分別指向當(dāng)前元素和下一個(gè)帶比較的元素。

index初始為nums[0],這里一開始我還在想為什么不是從0開始放,其實(shí)想錯(cuò)了。。。。。。。。。。。。。。。。。。慢慢悟道吧?。?!

向AI問(wèn)一下細(xì)節(jié)

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

AI