Remove Duplicates from Sorted Array II

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   for   art   cti   

Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

 移除排序數組中重複數目超過三個的部分,最後最多隻能重複兩次。

其實這樣的題目做了很多次,變種也很多,比如要求移除重複元素,即上述數組變成A=[3],還有剩餘單獨元素,即A=[1,2,3]。其實這些方法都是有規律的,此代碼的主要思想是利用一個標識isRepeated來標誌重複字串,看是否重複,根據isRepeated由true到false和由false到true的轉換,來移動src的指標,從而達到刪除多餘重複元素的目的,同樣的,假設本題的意思是想求去重複元素的話,則只需要把else中的startPosition++;這一行刪除即可,就可以得到一個不含重複數位數組(即[1,2,3,3,4,4,5]->[1,2,3,4,5])。如果想要完全刪除那些元素的話,就需要略微動一下腦子了,不過都是相通的。代碼看下面吧。

int removeDuplicates(int A[],int n) {    if (A == NULL || n == 0) return 0;    int startPosition = 0;    bool isRepeated = false;    for (int i = 1; i < n; i++) {        if (A[i] != A[startPosition]) {            isRepeated = false;            startPosition++;            A[startPosition] = A[i];        } else {            if (isRepeated == false) {                startPosition++;                A[startPosition] = A[i];                isRepeated = true;            }        }    }    return startPosition + 1;}//重複資料刪除的元素[1,2,2,3,4,4,5]->[1,3,5]int removeDuplicates(int A[],int n) {    if (A == NULL || n == 0) return 0;    int startPosition = 0;    bool isRepeated = false;    for (int i = 1; i < n; i++) {        if (A[i] != A[startPosition]) {    if(isRepeated==false) startPosition++;    A[startPosition] = A[i];    isRepeated = false;        } else {    isRepeated=true;        }    }    return startPosition + 1;}

多總結,加油開心每一天。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.