[Leetcode] 51. 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.

解題之法

class Solution {
public:
    int removeDuplicates(vector<int>& A) {
        int n = A.size();
        if (n <= 1) return n;
        int pre = 0, cur = 0;
        while (cur < n) {
            if (A[cur] == A[pre]) ++cur;
            else A[++pre] = A[cur++];
        }
        return pre + 1;
    }
};

分析

這道題要我們從有序數(shù)組中去除重復(fù)項(xiàng),我們使用快慢指針來記錄遍歷的坐標(biāo),最開始時(shí)兩個(gè)指針都指向第一個(gè)數(shù)字,如果兩個(gè)指針指的數(shù)字相同,則快指針向前走一步,如果不同,則兩個(gè)指針都向前走一步,這樣當(dāng)快指針走完整個(gè)數(shù)組后,慢指針當(dāng)前的坐標(biāo)加1就是數(shù)組中不同數(shù)組的個(gè)數(shù),

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,901評(píng)論 0 33
  • LeetCode 26. Remove Duplicates from Sorted Array Given a ...
    stevewang閱讀 355評(píng)論 3 1
  • 27. Remove Element Given an array and a value, remove all...
    exialym閱讀 309評(píng)論 0 0
  • 今天,當(dāng)我在秦嶺山中一個(gè)中蜂養(yǎng)殖場(chǎng)參觀,正在我想拍蜂王的照片的時(shí)候,突然,我被一只飛舞的中蜂“狠狠”地蟄了一下。 ...
    鄧文偉閱讀 303評(píng)論 0 0
  • 晚飯過后照例是散步。 人間四月天,夕陽(yáng)正好,吐穗與結(jié)籽的聲音鋪天蓋地。但我從不一個(gè)人走路,因?yàn)槟闵磉厸]伴,會(huì)把所有...
    劉小昭閱讀 1,084評(píng)論 1 4

友情鏈接更多精彩內(nèi)容